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

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

问题描述

我有两本字典,但为了简单起见,我会选择这两本:

<预><代码>>>>x = dict(a=1, b=2)>>>y = dict(a=2, b=2)

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

<预><代码>>>>对于 zip(x.iteritems(), y.iteritems()) 中的 x_values、y_values:如果 x_values == y_values:打印确定"、x_values、y_values别的:打印 'Not'、x_values、y_values

它可以工作,因为返回一个 tuple 然后比较相等性.

我的问题:

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

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

解决方案

如果你想知道有多少值在两个字典中匹配,你应该说:)

也许是这样的:

shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}打印 len(shared_items)

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

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

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

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

My questions:

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

Maybe something like this:

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天全站免登陆