Look up a key in a chain of Python dicts?

≯℡__Kan透↙ 提交于 2019-12-11 06:36:31

问题


Is there a built-in way in Python to look up a key k in a dict d and, if the key is not present, look it up instead in another dict e?

Can this be extended to an arbitrarily long chain of dicts d => e => f => ...?


回答1:


You could use a collections.ChainMap:

from collections import ChainMap

d = ChainMap({'a': 1, 'b': 2}, {'b': 22}, {'c': 3})
print(d['c'])
print(d['b'])

This would output:

3
2

Notice that the lookup for key 'b' was satisfied by the first dictionary in the map and the remaining dicts where not searched.

ChainMap was introduced in Python 3.3




回答2:


If you're using Python < 3.3, ChainMap isn't available.

This is less elegant, but works:

a = {1: 1, 2: 2}
b = {3: 3, 4: 4}

list_dicts = [a, b]

def lookup(key):
    for i in list_dicts:
        if key in i:
            return i[key]
    raise KeyError

lookup(1) # --> 1
lookup(4) # --> 4

You add all the dicts to a list, and use a method to look over them.




回答3:


May be like below:

if k in d:
    pass
elif k in e:
    pass
elif k in f:
    ...


来源:https://stackoverflow.com/questions/46644641/look-up-a-key-in-a-chain-of-python-dicts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!