Search code examples
pythondictionarykeylookupchain

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 chain of dicts d => e => f => ...?


Solution

  • 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