# Here's the gist of it, watch the video for more details.
dict1 = {
"a": 1,
"b": 2,
"c": 3,
}
dict2 = {
"d": 4,
"f": 0,
}
dict3 = {
"g": 6,
"h": 7,
"f": 10,
}
dicts = (dict1, dict3, dict2)
key = "f"from collections import ChainMap
python
collections
ChainMap
python-standard-library
Perform a look up over more that one dictionary with this elegant solution.
The built-in collections module is a handy bag of tools to be aware of. Here we explore collections.ChainMap, an elegant solution to efficiently carry out a look up over more than one dictionary.
for d in dicts:
val = d.get(key)
if val is not None:
print(val)
break10
from collections import ChainMap
ChainMap(*dicts)[key]10
/Fin
Any bugs, questions, comments, suggestions? Ping me on twitter or drop me an e-mail (fabridamicelli at gmail).
Share this article on your favourite platform: