获取字典中匹配键的值 [英] Get values for matching keys in dictionaries

查看:280
本文介绍了获取字典中匹配键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个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屋!

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