Look Up A Key In A Chain Of Python Dicts?
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 c
Solution 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
Solution 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]
deflookup(key):for i in list_dicts:if key in i:returni[key]raiseKeyErrorlookup(1)# --> 1lookup(4)# --> 4
You add all the dicts to a list, and use a method to look over them.
Solution 3:
May be like below:
if k in d:
passelif k in e:
passelif k in f:
...
Post a Comment for "Look Up A Key In A Chain Of Python Dicts?"