Francis Francis - 3 months ago 12
Python Question

Create a new list from two dictionaries

This is a question about Python. I have the following list of dictionaries:

listA = [
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "c2": 5, "id": "333"},
{"t": 5, "tid": 6, "gtm": 3, "c1": 4, "c2": 5, "id": "444"}
]


and a dictionary I wanted to compare with:

dictA = {"t": 1, "tid": 2, "gtm": 3}


I wanted to create a list of dicts that match all the items in dictA from listA and to include the "id" field as well:

listB = [
{"t": 1, "tid": 2, "gtm": 3, "id": "111"},
{"t": 1, "tid": 2, "gtm": 3, "id": "333"}
]


I tried doing this:

for k in listA:
for key, value in k.viewitems() & dictA.viewitems():
print key, value


But it's matching any item in dictA.

Answer

You would need to check the length of the intersection, just checking if dct.viewitems() & dictA.viewitems() would evaluate to True for any intersection :

[dct for dct in listA if len(dct.viewitems() & dictA.viewitems()) == len(dictA)]

Or just check for a subset, if the items from dictA are a subset of each dict:

[dct for dct in listA if dictA.viewitems() <= dct.viewitems()]

Or reverse the logic looking for a superset:

 [dct for dct in listA if dct.viewitems() >= dictA.viewitems()]