You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用变量引用Python嵌套字典的键

使用变量访问Python嵌套字典的键

你有如下嵌套字典:

example = {'a': {'b': 'hi'}, 'c': 1}

想要通过包含单键和嵌套键列表的变量 keys = ['c', ['a','b']] 遍历取值,期望输出:

1
hi

实现方法

直接用example[key]无法处理嵌套键列表的情况,需要写一个辅助函数来逐层解析嵌套键:

def get_nested_val(d, keys):
    if not isinstance(keys, list):
        return d[keys]
    current = d
    for k in keys:
        current = current[k]
    return current

example = {'a': {'b': 'hi'}, 'c': 1}
keys = ['c', ['a','b']]

for key in keys:
    print(get_nested_val(example, key))

运行这段代码就能得到你想要的输出。函数会自动判断传入的键是单个值还是嵌套列表:如果是单个键直接返回对应值;如果是列表,则逐层遍历嵌套字典直到取到最终值。

内容的提问来源于stack exchange,提问作者keynesiancross

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:15:40