获取字典中匹配键的值 [英] Get values for matching keys in dictionaries
问题描述
我有两个OrderedDict
字典,我想在两个字典中检索匹配键的值:
I have two OrderedDict
dictionaries, and I want to retrieve values for matching keys in both dictionaries:
>>> from collections import OrderedDict
>>> d1 = OrderedDict()
>>> d2 = OrderedDict()
>>> d1["A"] = 2
>>> d1["B"] = 3
>>> d1["C"] = 2
>>> d2["D"] = 90
>>> d2["B"] = 11
>>> d2["C"] = 25
>>> # search both dicts and output values where key matches
(3, 11)
(2, 25)
推荐答案
print [(d1[key], d2[key]) for key in d1.viewkeys() & d2]
# [(2, 25), (3, 11)]
d1.viewkeys() & d2
用于获取两个词典中都存在的键.一旦得到,只需从两个字典中获取与之对应的值即可.
d1.viewkeys() & d2
is used to get the keys which are present in both the dictionaries. Once we get that, simply get the values corresponding to that from both the dictionaries.
之所以可行,是因为根据字典视图对象Python 2.7文档,
This works because, as per the Dictionary View Objects Python 2.7 Documentation,
键视图是类似集合的,因为它们的条目是唯一且可哈希的.
Keys views are set-like since their entries are unique and hashable.
由于viewkeys
已经是集合式的,所以我们可以直接在它们上使用集合操作.
Since viewkeys
are already set-like, we can use set operations on them directly.
注意::如果您使用的是Python 3.x,则必须使用keys
函数,例如
Note: If you are using Python 3.x, then you have to use keys
function, like this
print([(d1[key], d2[key]) for key in d1.keys() & d2])
因为,按照字典视图对象Python 3.x文档,
由dict.keys(),dict.values()和dict.items()返回的对象是视图对象.
The objects returned by dict.keys(), dict.values() and dict.items() are view objects.
由于keys
本身返回一个视图对象,并且由于它们的条目是唯一且可哈希的,因此我们可以像set那样使用它.
Since keys
itself returns a view object, and as their entries are unique and hashable, we can use that like set.
注意:在Python 2.x中,dict.keys
返回键列表.由于我们无法对列表进行设置操作,因此我们无法使用Python 3.x解决方案.
Note: In Python 2.x, dict.keys
returns a list of keys. Since we cannot do set operations on a list, we cannot use the Python 3.x solution.
这篇关于获取字典中匹配键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!