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

如何更新Python嵌套字典(nested dict)中的键

修改嵌套字典中的键

方法一:直接修改特定键

针对你的场景,要修改user1下的food和drinks键,按「取值→新增键→删除原键」的步骤操作即可:

# 处理"food"键
food_data = d["user1"]["food"]
d["user1"]["NEW VALUE"] = food_data
del d["user1"]["food"]

# 处理"drinks"键
drinks_data = d["user1"]["drinks"]
d["user1"]["SECOND VALUE"] = drinks_data
del d["user1"]["drinks"]

执行后,d["user1"]就会变成你想要的结构。

方法二:通用函数(适配动态结构)

因为你的应用中用户、文件夹数量都是动态的,写一个通用函数可以更灵活地修改任意层级的键:

def rename_nested_key(target_dict, key_path, new_key_name):
    # 定位到目标键的父级字典
    parent = target_dict
    for key in key_path[:-1]:
        parent = parent[key]
    # 转移原键的值到新键
    parent[new_key_name] = parent[key_path[-1]]
    # 删除原键
    del parent[key_path[-1]]

# 调用示例
rename_nested_key(d, ["user1", "food"], "NEW VALUE")
rename_nested_key(d, ["user1", "drinks"], "SECOND VALUE")

这个函数无需关心字典嵌套深度,只要传入键的路径(比如["user1", "food"]表示user1下的food键)和新键名,就能完成修改。

注意事项

  • 确保key_path中的每个键都存在于字典中,否则会触发KeyError;如果需要容错,可以在函数中添加try-except或键存在性检查。
  • 单线程应用无需额外处理,多线程环境下修改字典时建议加锁避免冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:00:31