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

如何检查分层字典的键是否存在并动态创建不存在的键?

更简洁的动态嵌套字典条目创建方案

你的现有代码能实现需求,但嵌套的if-else判断过于冗余,以下是几种更简洁、高效的替代方案:

原始代码回顾

example_dict = {'jack' : {'long' : {'color' : 'red'}}}

name = 'jane'
hair = 'short'
color = 'color'
shade = 'blue'

if name not in example_dict:
    example_dict[name] = {hair : {color : shade}}
else:
    if hair not in example_dict[name]:
        example_dict[name][hair] = {color : shade}
    else:
        if color not in example_dict[name][hair]:
            example_dict[name][hair][color] = shade
        else:
            example_dict[name][hair][color] = shade

print(example_dict)

方案1:链式调用dict.setdefault()

利用setdefault()方法的特性——不存在指定键时创建并返回默认值,存在则返回对应值,可链式处理嵌套结构:

example_dict = {'jack' : {'long' : {'color' : 'red'}}}

name = 'jane'
hair = 'short'
color = 'color'
shade = 'blue'

# 逐层处理嵌套键,自动创建不存在的条目
example_dict.setdefault(name, {}).setdefault(hair, {})[color] = shade

print(example_dict)

该方法完全匹配你原代码的逻辑:不管内层键是否存在,最终都会将color对应的值设为shade,代码量大幅减少。

方案2:使用collections.defaultdict(适合频繁嵌套场景)

通过递归定义的defaultdict,可自动创建嵌套字典结构,直接赋值即可完成动态条目创建:

from collections import defaultdict

# 递归生成嵌套的defaultdict
def nested_defaultdict():
    return defaultdict(nested_defaultdict)

# 初始化并填充原始数据
example_dict = nested_defaultdict()
example_dict['jack']['long']['color'] = 'red'

name = 'jane'
hair = 'short'
color = 'color'
shade = 'blue'

# 直接赋值,不存在的键会自动创建
example_dict[name][hair][color] = shade

# 如需转为普通字典,使用dict()转换
print(dict(example_dict))

这种方式无需手动判断键是否存在,适合需要频繁创建多层嵌套字典的场景。

方案3:一行式实现(基于setdefault)

如果追求极致简洁,可将变量整合后用一行代码完成:

example_dict = {'jack' : {'long' : {'color' : 'red'}}}
name, hair, color, shade = 'jane', 'short', 'color', 'blue'

example_dict.setdefault(name, {}).setdefault(hair, {})[color] = shade

print(example_dict)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:24:17