问题描述
我有两本字典,但为了简单起见,我会选择这两本:
>>>x = dict(a=1, b=2)>>>y = dict(a=2, b=2)现在,我要比较 x
中的每个 key, value
对是否在 y
中具有相同的对应值.所以我写了这个:
它可以工作,因为返回一个 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)
这篇关于比较两个字典并检查有多少(键,值)对相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!