在Python字典链中查找键? [英] Look up a key in a chain of Python dicts?

查看:127
本文介绍了在Python字典链中查找键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中是否有内置方法在dict d中查找键k,如果不存在该键,则在另一个dict e中查找它?

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?

这可以扩展到dict s d => e => f => ...的任意长链吗?

Can this be extended to an arbitrarily long chain of dicts d => e => f => ...?

推荐答案

您可以使用 collections.ChainMap :

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'])

这将输出:


3
2

请注意,键'b'的查找已由地图中的第一个词典以及未搜索到的其余字典满足.

Notice that the lookup for key 'b' was satisfied by the first dictionary in the map and the remaining dicts where not searched.

ChainMap在Python 3.3中引入

ChainMap was introduced in Python 3.3

这篇关于在Python字典链中查找键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆