简体   繁体   中英

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.

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)

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
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM