fabero
fabero

Reputation: 85

Comparing two lists of dictionaries in Python

I would like to make a function that compares two lists of dictionaries in python by looking at their keys. When list A contains a dictionary that has an entry with the same key as an entry in the dictionary in list B, the function should return True.

Here's an example of list A and B:

listA = [{'key1':'value1'}, {'key2':'value2'}]
listB = [{'key1':'value3'}, {'key3':'value4'}]

In this example the function should return True, because key1 is a match.

Thanks in advance.

Upvotes: 0

Views: 500

Answers (2)

Noctis Skytower
Noctis Skytower

Reputation: 22041

Is this what you are looking for?

def cmp_dict(a, b):
    return any(frozenset(c) & frozenset(d) for c, d in zip(a, b))

Here is a demonstration of its usage:

>>> listA = [{'key1':'value1'}, {'key2':'value2'}]
>>> listB = [{'key1':'value3'}, {'key3':'value4'}]
>>> cmp_dict(listA, listB)
True
>>> 

Upvotes: 0

Leo
Leo

Reputation: 1845

first you have to take the keys out of the list of dictionaries, then compare.

keysA = [k for x in listA for k in x.keys()]
keysB = [k for x in listB for k in x.keys()]

any(k in keysB for k in keysA)

Upvotes: 2

Related Questions