Python多字典比较 [英] python multiple dict compare
问题描述
我有一个字典,想与另外三个字典进行比较.如果3个字典中的任何一个都不存在key,则用该键和值对创建一个新字典,此外,如果3个字典中的任何一个键和值都匹配,并且key存在但值不同,则跳过然后再创建一个字典.
I have one dict and want to compare with 3 more dict. If key does not exist in any of the 3 dict, then to create a new dict with that key, value pair, Also, skip if the key and value both match in any of the 3 dict, and if key exist but value is different then create a one more dict.
a={'a':1,'b':2,'c':3,'d':4}
b={'a':10,'b':20}
c={'p':100,'q':200,'c':300}
d={'a':1000,'x':2000,'c':3}
将dict a与b,c和d比较之后.结果应为 p_dict = {'d':4}
和 q_dict = {'a':1,'b':2}
After comparing dict a with b,c and d. The result should be p_dict = {'d':4}
and q_dict = {'a':1,'b':2}
我正在考虑多个for循环,但是在比较字典a和b之后,它将再创建2个字典,这会使过程复杂化.有人有更好的主意吗?
I am thinking for multiple for loops but it will create 2 more dict after comparing dict a and b and it will complicate process. Does anyone have better idea?
推荐答案
这是Python 3.3的解决方案.这也可以在Python 2.7中使用,但是我将使用 .iteritems()
代替 .items()
:
Here's a solution for Python 3.3. This also works in Python 2.7, but there I would use .iteritems()
instead of .items()
:
>>> a = {"a":1, "b":2, "c":3, "d":4}
>>> b = {"a":10, "b":20}
>>> c = {"p":100, "q":200, "c":300}
>>> d = {"a":1000, "x":2000, "c":3}
>>> p_dict = {k:v for k,v in a.items()
... if not any(k in dicts for dicts in (b,c,d))}
>>> p_dict
{'d': 4}
>>> q_dict = {k:v for k,v in a.items()
... if any(k in dicts for dicts in (b,c,d))
... and not any(dicts.get(k)==v for dicts in (b,c,d))}
>>> q_dict
{'a': 1, 'b': 2}
这假设您字典中的所有值都不是 None
.
This assumes that none of the values in your dicts are None
.
这篇关于Python多字典比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!