Pythonic的方式来检查两个字典是否具有相同的键? [英] Pythonic way to check if two dictionaries have the identical set of keys?
问题描述
d_1 = {'peter':1,'adam' 2,'david':3}
和
d_2 = {'peter':14,'adam':44,'david':33,'alan':21}
最明智的方法是检查两个字典是否包含相同的一组键?在上面的例子中,应该返回 False
,因为 d_2
包含'alan'
键,其中 d_1
不。请注意,我不感兴趣检查每个键的关联值是否相同,只是该组键是相同的。
您可以使用dict.keys()获取字典的键。
您可以将其转换为set(dict.keys ())
您可以将集合与==
进行比较总结:
set(d_1.keys())== set(d_2.keys())
将给你你想要的。
For example, let's say I have to dictionaries:
d_1 = {'peter': 1, 'adam': 2, 'david': 3}
and
d_2 = {'peter': 14, 'adam': 44, 'david': 33, 'alan': 21}
What's the cleverest way to check whether the two dictionaries contain the same set of keys? In the example above it should return False
because d_2
contains the 'alan'
key, which d_1
doesn't. Please note that I am not interested in checking that the associated values for each and every key are the same, just that the set of keys are the same.
You can get the keys for a dictionary with dict.keys().
You can turn this into a set with set(dict.keys())
You can compare sets with ==
To sum up:
set(d_1.keys()) == set(d_2.keys())
will give you what you want.
这篇关于Pythonic的方式来检查两个字典是否具有相同的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!