比较两个字典并检查多少对(键,值)相等 [英] Comparing two dictionaries and checking how many (key, value) pairs are equal

查看:100
本文介绍了比较两个字典并检查多少对(键,值)相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字典,为简单起见,我将采用这两个字典:

I have two dictionaries, but for simplification, I will take these two:

>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)

现在,我想比较x中的每个key, value对是否在y中具有相同的对应值.所以我写了这个:

Now, I want to compare whether each key, value pair in x has the same corresponding value in y. So I wrote this:

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

它是有效的,因为返回了tuple然后比较了相等性.

And it works since a tuple is returned and then compared for equality.

我的问题:

这是正确的吗?有没有一种更好的方法来做到这一点?最好不要提速,我是在讲代码优雅.

Is this correct? Is there a better way to do this? Better not in speed, I am talking about code elegance.

更新:我忘了提到我必须检查多少对key, value是相等的.

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 = {k: x[k] for k in x if k in y and x[k] == y[k]}
print len(shared_items)

这篇关于比较两个字典并检查多少对(键,值)相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆