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

如何向Python多维字典添加值?键不存在时需自动创建

优雅处理Python多维字典的层级键创建与赋值

问题场景

需要向嵌套多层的Python字典中添加值,各级键可能存在也可能不存在:若键已存在则直接赋值,若不存在则自动创建对应层级的键。现有实现代码冗余繁琐,需优化。

原始实现代码

if response.get('pages', {}).get(url, {}).get('variations', {}).get('custom_screenshot'):
    response['pages'][url]['variations']['custom_screenshot'][command.get('params')[0]] = output
elif response.get('pages', {}).get(url, {}).get('variations'):
    response['pages'][url]['variations']['custom_screenshot'] = {command.get('params')[0]: output}
elif response.get('pages', {}).get(url, {}):
    response['pages'][url]['variations'] = {'custom_screenshot': {command.get('params')[0]: output}}
elif response.get('pages', {}):
    response['pages']['url'] = {'variations': {'custom_screenshot': {command.get('params')[0]: output}}}
else:
    response['pages'] = {url: {'variations': {'custom_screenshot': {command.get('params')[0]: output}}}}

return response

最优实现方案

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

无需导入任何模块,利用字典内置的setdefault方法自动创建缺失层级,代码极简:

# 提取参数键提升可读性
param_key = command.get('params')[0]

# 链式调用自动创建所有缺失的层级
response.setdefault('pages', {})\
         .setdefault(url, {})\
         .setdefault('variations', {})\
         .setdefault('custom_screenshot', {})[param_key] = output

return response

原理:setdefault(key, default)检查字典中是否存在指定key,存在则返回对应值;不存在则将key设为default值并返回,因此可链式调用逐层构建嵌套结构。

方案2:使用collections.defaultdict递归创建嵌套字典

适合频繁操作多层嵌套字典的场景,预先定义递归默认字典类型:

from collections import defaultdict

# 定义递归嵌套的默认字典
def nested_defaultdict():
    return defaultdict(nested_defaultdict)

# 若response初始不是defaultdict类型,可转换(可选)
if not isinstance(response, defaultdict):
    response = nested_defaultdict()

# 直接赋值,不存在的键会自动创建
response['pages'][url]['variations']['custom_screenshot'][param_key] = output

# 如需转回普通字典(可选)
def defaultdict_to_dict(d):
    return {k: defaultdict_to_dict(v) if isinstance(v, defaultdict) else v for k, v in d.items()}
response = defaultdict_to_dict(response)

return response

方案3:通用嵌套赋值函数(适配任意深度)

通过遍历键路径实现通用赋值,灵活适配不同嵌套层级:

def nested_assign(d, keys, value):
    current = d
    # 遍历除最后一个键外的所有层级
    for key in keys[:-1]:
        current = current.setdefault(key, {})
    # 给最后一个键赋值
    current[keys[-1]] = value

# 定义键路径与参数
param_key = command.get('params')[0]
key_path = ['pages', url, 'variations', 'custom_screenshot', param_key]

# 调用函数完成赋值
nested_assign(response, key_path, output)

return response

方案对比

  • setdefault链式调用:最轻量化,原生支持,代码简洁,适合单次或少量嵌套赋值场景。
  • defaultdict递归:适合频繁操作嵌套字典的场景,赋值无需手动处理层级,但需按需转换类型。
  • 通用嵌套函数:扩展性最强,支持任意深度的键路径,适合复用嵌套赋值逻辑的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:20:32