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

如何在Python中遍历嵌套字典?提取指定键值列表

问题1:如何在Python中遍历嵌套字典?

遍历嵌套字典是Python里很常见的需求,我给你整理几个实用的方法,按需选择就行:

1. 递归遍历(适合未知嵌套深度的情况)

如果不确定字典嵌套了多少层,递归是最省心的方式,写个函数就能自动遍历所有层级:

def traverse_nested_dict(nested_dict):
    for key, value in nested_dict.items():
        if isinstance(value, dict):
            print(f"进入子字典:{key}")
            traverse_nested_dict(value)
        else:
            print(f"键: {key}, 值: {value}")

# 示例调用
sample_dict = {
    'a': 1,
    'b': {'c': 2, 'd': {'e': 3}}
}
traverse_nested_dict(sample_dict)

2. 嵌套循环(适合固定嵌套层数的情况)

如果明确知道字典的嵌套层级(比如两层),直接用嵌套循环就够了,简单直观:

sample_dict = {
    'BCH/BTC': {'active': True, 'base': 'BCH'},
    'BCH/EUR': {'active': True, 'base': 'BCH'}
}

# 遍历两层字典
for pair, details in sample_dict.items():
    print(f"交易对: {pair}")
    for key, value in details.items():
        print(f"  {key}: {value}")

3. 迭代式遍历(用栈/队列,避免递归深度问题)

如果嵌套深度特别大,递归可能会触发RecursionError,这时候用栈或者队列来实现迭代遍历更稳妥:

def traverse_iterative(nested_dict):
    stack = [(nested_dict, "")]
    while stack:
        current_dict, path = stack.pop()
        for key, value in current_dict.items():
            current_path = f"{path}.{key}" if path else key
            if isinstance(value, dict):
                stack.append((value, current_path))
            else:
                print(f"路径: {current_path}, 值: {value}")

# 示例调用
traverse_iterative(sample_dict)

问题2:提取嵌套字典中指定键的值

针对你的需求,用列表推导式就能简洁高效地实现,我结合你的示例一步步拆解:

第一步:明确数据结构

假设你的列表是这样的(对应你描述的2个字典,每个包含3个子字典):

market_list = [
    {
        'BCH/BTC': {'active': True, 'base': 'BCH'},
        'BCH/EUR': {'active': True, 'base': 'BCH'},
        'BCC/USD': {'active': False, 'base': 'BCC'}
    },
    {
        'ZEC/BTC': {'active': True, 'base': 'ZEC'},
        'ZRX/EUR': {'active': True, 'base': 'ZRX'},
        'ZAC/USD': {'active': False, 'base': 'ZAC'}
    }
]

第二步:提取指定键的值

一行代码就能得到你想要的bases列表:

bases = [[sub_dict['base'] for sub_dict in parent_dict.values()] for parent_dict in market_list]

# 输出结果
print(bases[0])  # ['BCH', 'BCH', 'BCC']
print(bases[1])  # ['ZEC', 'ZRX', 'ZAC']

第三步:扩展与异常处理

  • 如果要提取其他键(比如active),只需要把'base'换成对应的键即可:
    actives = [[sub_dict['active'] for sub_dict in parent_dict.values()] for parent_dict in market_list]
    
  • 担心子字典里没有目标键?用get()方法避免KeyError,还能设置默认值:
    bases = [[sub_dict.get('base', '未知') for sub_dict in parent_dict.values()] for parent_dict in market_list]
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:28:58