比较由python中的字典和唯一键组成的2个列表 [英] Comparing 2 lists consisting of dictionaries with unique keys in python
问题描述
我有2个列表,两个列表包含相同数量的字典。每个字典都有一个唯一的键。对于第二列表中的第一列表的每个字典存在匹配,即具有唯一键的字典存在于另一列表中。但是这2个字典的其他元素可能不同。例如:
I have 2 lists, both of which contain same number of dictionaries. Each dictionary has a unique key. There is a match for each dictionary of the first list in the second list, that is a dictionary with a unique key exists in the other list. But the other elements of such 2 dictionaries may vary. For example:
list_1 = [
{
'unique_id': '001',
'key1': 'AAA',
'key2': 'BBB',
'key3': 'EEE'
},
{
'unique_id': '002',
'key1': 'AAA',
'key2': 'CCC',
'key3': 'FFF'
}
]
list_2 = [
{
'unique_id': '001',
'key1': 'AAA',
'key2': 'DDD',
'key3': 'EEE'
},
{
'unique_id': '002',
'key1': 'AAA',
'key2': 'CCC',
'key3': 'FFF'
}
]
我想比较2个匹配字典的所有元素。如果任何元素不相等,我想打印不等于的元素。
I want to compare all elements of 2 matching dictionaries. If any of the elements are not equal, I want to print the none-equal elements.
请帮助,
谢谢
最好的问候
Thanks Best Regards
推荐答案
假设dicts像你的示例输入一样排列,使用 zip()
函数获取关联的对的列表,然后可以使用 any()
检查是否有区别:
Assuming that the dicts line up like in your example input, you can use the zip()
function to get a list of associated pairs of dicts, then you can use any()
to check if there is a difference:
>>> list_1 = [{'unique_id':'001', 'key1':'AAA', 'key2':'BBB', 'key3':'EEE'},
{'unique_id':'002', 'key1':'AAA', 'key2':'CCC', 'key3':'FFF'}]
>>> list_2 = [{'unique_id':'001', 'key1':'AAA', 'key2':'DDD', 'key3':'EEE'},
{'unique_id':'002', 'key1':'AAA', 'key2':'CCC', 'key3':'FFF'}]
>>> pairs = zip(list_1, list_2)
>>> any(x != y for x, y in pairs)
True
不同的对:
>>> [(x, y) for x, y in pairs if x != y]
[({'key3': 'EEE', 'key2': 'BBB', 'key1': 'AAA', 'unique_id': '001'}, {'key3': 'EEE', 'key2': 'DDD', 'key1': 'AAA', 'unique_id': '001'})]
您甚至可以得到不匹配每个键的键:
You can even get the keys which don't match for each pair:
>>> [[k for k in x if x[k] != y[k]] for x, y in pairs if x != y]
[['key2']]
可能与相关值一起:
>>> [[(k, x[k], y[k]) for k in x if x[k] != y[k]] for x, y in pairs if x != y]
[[('key2', 'BBB', 'DDD')]]
strong>如果你的输入列表还没有排序,你也可以这样做:
NOTE: In case you're input lists are not sorted yet, you can do that easily as well:
>>> from operator import itemgetter
>>> list_1, list_2 = [sorted(l, key=itemgetter('unique_id'))
for l in (list_1, list_2)]
这篇关于比较由python中的字典和唯一键组成的2个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!