from collections import ChainMap

python
collections
ChainMap
python-standard-library
An elegant solution to efficiently carry out a look up over more than one dictionary.
Author

Fabrizio Damicelli

Published

January 29, 2022

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.

# 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"
for d in dicts:
    val = d.get(key)
    if val is not None:
        print(val)
        break
10
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: