如何通过列表索引Python嵌套字典中的对应值?
实现列表式访问嵌套字典的值
方法一:编写通用取值函数
写一个简单的遍历函数,依次按列表中的键逐层访问嵌套字典:
def get_nested_value(d, keys): current = d for key in keys: current = current[key] return current # 测试示例 d = {'a': {'b': {'c': {'d': 0}}}} list1 = ['a', 'b'] list2 = ['a', 'b', 'c'] list3 = ['a', 'b', 'c', 'd'] print(get_nested_value(d, list1)) # 输出: {'c': {'d': 0}} print(get_nested_value(d, list3)) # 输出: 0
如果需要处理键不存在或中途遇到非字典类型的异常,可以给函数添加默认值返回逻辑:
def get_nested_value(d, keys, default=None): current = d try: for key in keys: current = current[key] return current except (KeyError, TypeError): return default # 测试异常情况 print(get_nested_value(d, ['a', 'x'], default='键不存在')) # 输出: 键不存在
方法二:自定义字典类支持列表索引
如果想直接用d[list]的原生语法访问,可以继承dict重写__getitem__方法,让字典原生支持列表作为索引:
class NestedDict(dict): def __getitem__(self, keys): # 非列表类型按普通字典逻辑处理 if not isinstance(keys, list): return super().__getitem__(keys) current = self for key in keys: current = current[key] return current # 测试示例 d = NestedDict({'a': {'b': {'c': {'d': 0}}}}) print(d[list1]) # 输出: {'c': {'d': 0}} print(d[list3]) # 输出: 0 # 同时保留普通字典的访问方式 print(d['a']) # 输出: {'b': {'c': {'d': 0}}}
内容的提问来源于stack exchange,提问作者Oliver
相关产品推荐
相关产品推荐

