在Python中比较两个字典 [英] Comparing two dictionaries in Python
本文介绍了在Python中比较两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个字典,但为了简化,我将采用这两个字典:
I have two dictionaries, but for simplification, I will take these two:
>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)
现在, code>键中的键具有相同的值,
x
>。所以我写了:
>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
if x_values == y_values:
print 'Ok', x_values, y_values
else:
print 'Not', x_values, y_values
返回
我的问题:
这正确吗?有没有更好的方法来做这个?
Is this correct? Is there a better way to do this? Better not in speed, I am talking about code elegance.
更新:我忘了提及我必须检查多少键,值
对是相等的。
UPDATE: I forgot to mention that I have to check how many key, value
pairs are equal.
推荐答案
如果你想知道在这两个词典中匹配多少个值,你应该说:)
If you want to know how many values match in both the dictionaries, you should have said that :)
可能是这样的:
shared_items = set(x.items()) & set(y.items())
print len(shared_items)
这篇关于在Python中比较两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文