在Python中搜索多个词典中的键的最佳方法是什么

时间:2014-06-24 20:06:01

标签: python dictionary

我知道我们可以像这样搜索Python中的密钥:

if key in myDict:
    #Do something here

我知道我们可以扩展它并使用elif语句

在多个词典中搜索密钥
if key in myDict_1:
    #Do something here
elif key in myDict_2:
    #Do something here

或通过

if key in (myDict_1.keys() + myDict_2.keys()):
    #Do something here

但有没有更简洁的方法在两个不同的dicts中搜索Python中的键而不使用if-else或明确添加键列表?

4 个答案:

答案 0 :(得分:2)

你写的问题的答案是:

if any(key in d for d in dicts):
    # do something

如果您需要知道哪个字典或词典包含密钥,您可以使用itertools.compress()

>>> d1 = dict(zip("kapow", "squee"))
>>> d2 = dict(zip("bar", "foo"))
>>> d3 = dict(zip("xyz", "abc"))
>>> dicts = d1, d2, d3

>>> from pprint import pprint
>>> pprint(dicts)
({'a': 'q', 'k': 's', 'o': 'e', 'p': 'u', 'w': 'e'},
{'a': 'o', 'b': 'f', 'r': 'o'},
{'x': 'a', 'y': 'b', 'z': 'c'})

>>> from itertools import compress
>>> for d_with_key in compress(dicts, ("a" in d for d in dicts)):
...     print(d_with_key)
... 
{'a': 'q', 'p': 'u', 'k': 's', 'w': 'e', 'o': 'e'}
{'a': 'o', 'r': 'o', 'b': 'f'}

答案 1 :(得分:1)

正确的方式是Zero写道:

if any(key in d for d in dicts): # do something

在阅读下面的评论后修复,感谢@jwodder:

但您也可以使用itertools.chain函数创建两个(或更多)字典的键的元组。

>>> a = {1:2}
>>> b = {3:4}
>>> c = {5:6, 7:8}
>>> print(tuple(itertools.chain(a, b, c)))
(1, 3, 5, 7)

所以你也可以:

if x in tuple(itertools.chain(a, b, c)):
    # Do something

答案 2 :(得分:1)

这里也可以有一点列表理解;如果您只是想确定一个密钥是否在一个容器中,any()就是这样做的;如果你想得到dict(或dicts)并与之合作,也许这样就足够了:

>>> def get_dicts_with_key(some_key, *dicts):
...     return [d for d in dicts if some_key in d]

>>> dict1 = {"hey":123}
>>> dict2 = {"wait":456}
>>> get_dicts_with_key('hey', dict1, dict2)
[{'hey': 123}]
>>> get_dicts_with_key('wait', dict1, dict2)
[{'wait': 456}]
>>> get_dicts_with_key('complaint', dict1, dict2)
[]

如果密钥存在于任一dict中,则两者都将被返回,如下:

>>> dict1['complaint'] = 777
>>> dict2['complaint'] = 888
>>> get_dicts_with_key('complaint', dict1, dict2)
[{'complaint': 777, 'hey': 123}, {'complaint': 888, 'wait': 456}]
>>> 

答案 3 :(得分:0)

为什么不把你的dicts放在像列表这样的迭代中,然后简单的循环呢?你可以把它表达为这样的函数。

def has_key(key, my_dicts):
    for my_dict in my_dicts:
        if key in my_dict:
            return True
    return False

它会像这样使用。

>>> dict1 = {'a':1, 'b': 2}
>>> dict2 = {'b':10, 'c': 11}
>>> has_key('b', [dict1, dict2])
True