问题
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 dict
s 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