[英]Comparing dictionaries in Python lists
I have two lists which contain dictionaries.我有两个包含字典的列表。 Each dictionary has only one entry.
每本词典只有一个条目。 I would like to check if a key in dictionary A (in list X) also exists in a dictionary in list Y. If this is the case, the key and the values belonging to it should be printed.
我想检查字典 A 中的键(在列表 X 中)是否也存在于列表 Y 中的字典中。如果是这种情况,应该打印属于它的键和值。
Example:例子:
listA = [{key1: value1}, {key2: value2}]
listB = [{key1: value3}, {key4: value4}]
In this case the output should be:在这种情况下,输出应该是:
key1: value1, value3
Thanks in advance.提前致谢。
A very simple way to do it would be:一个非常简单的方法是:
#!/usr/bin/env python
l1 = [{'1':"one"} , {'2':"two"}]
l2 = [{'3':"three"} , {'1':"one_too"}]
def cmp(l1,l2):
for i in l1:
for j in l2:
for (key1,value1),(key2,value2) in zip(i.iteritems(),j.iteritems()):
if key1==key2:
print key1+": "+value1+", "+value2
break
cmp(l1,l2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.