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

使用Python列表构建三层嵌套字典时遇报错,求解决方案

三层嵌套字典构建报错的解决方法

问题描述

我原本用以下代码通过两个列表构建两层嵌套字典:

lvl1 = ['a', 'b']
lvl2 = ['apples','bananas']
results = defaultdict(dict)
for one in lvl1:
    for two in lvl2:
        results[one][two] = 0

但新增第三层列表后,用相同逻辑构建三层嵌套字典时出现报错:

lvl1 = ['a', 'b']
lvl2 = ['apples','bananas']
lvl3 = ['size','depth']
results = defaultdict(dict)

# 执行报错
for one in lvl1:
    for two in lvl2:
        for three in lvl3:
            results[one][two][three] = 0

期望输出:

{'a':{'apples':{'size':0, 'depth':0}, 'bananas':{'size':0, 'depth':0}},
 'b':{'apples':{'size':0, 'depth':0}, 'bananas':{'size':0, 'depth':0}}}

报错原因

原代码中results = defaultdict(dict)仅让第一层是自动生成字典的defaultdict,而第二层是普通字典。当执行results[one][two][three] = 0时,若results[one]中不存在two这个键,访问results[one][two]会直接抛出KeyError——普通字典不会自动创建不存在的键。

解决方法

方法1:使用嵌套的defaultdict

将results定义为嵌套的defaultdict,让第二层也具备自动创建字典的能力:

from collections import defaultdict

lvl1 = ['a', 'b']
lvl2 = ['apples','bananas']
lvl3 = ['size','depth']
# 第一层是defaultdict,第二层也是defaultdict,第三层是普通dict
results = defaultdict(lambda: defaultdict(dict))

for one in lvl1:
    for two in lvl2:
        for three in lvl3:
            results[one][two][three] = 0

# 若需要转为普通字典(可选)
results = dict(results)
print(results)

方法2:手动逐层初始化字典

在循环中先检查并创建第二层字典,再给第三层赋值:

lvl1 = ['a', 'b']
lvl2 = ['apples','bananas']
lvl3 = ['size','depth']
results = {}

for one in lvl1:
    if one not in results:
        results[one] = {}
    for two in lvl2:
        if two not in results[one]:
            results[one][two] = {}
        for three in lvl3:
            results[one][two][three] = 0

print(results)

方法3:使用字典推导式(更简洁)

通过嵌套字典推导式直接生成目标结构,无需循环赋值:

lvl1 = ['a', 'b']
lvl2 = ['apples','bananas']
lvl3 = ['size','depth']

results = {
    one: {
        two: {three: 0 for three in lvl3}
        for two in lvl2
    }
    for one in lvl1
}

print(results)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:26:25