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 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