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

Python如何通过字典路径直接设置对应字典条目的值

解决方案

报错原因说明

Python 原生字典仅支持单级键查询/赋值,你看到的元组路径访问语法不是原生默认支持的能力,是原帖中基于自定义扩展字典实现的功能,因此直接对普通字典使用会抛出KeyError。

方案1:自定义扩展字典实现目标语法

该方案完全支持你想要的kidshair[mypath] = 'black'写法,不需要调用额外的外部赋值函数:

class PathDict(dict):
    def __getitem__(self, path):
        if not isinstance(path, tuple):
            return super().__getitem__(path)
        current = self
        for key in path:
            current = current[key]
        return current
    
    def __setitem__(self, path, value):
        if not isinstance(path, tuple):
            super().__setitem__(path, value)
            return
        current = self
        for key in path[:-1]:
            current = current[key]
        current[path[-1]] = value

使用示例:

my_dict = {'allkids':{'child1':{'hair':'blonde'},
                      'child2':{'hair':'black'},
                      'child3':{'hair':'red'},
                      'child4':{'hair':'brown'}}}
# 将普通字典转为支持路径访问的扩展字典
kidshair = PathDict(my_dict)
mypath = ('allkids', 'child3', 'hair')

# 读取值
print(kidshair[mypath]) # 输出:red
# 按你想要的语法赋值
kidshair[mypath] = 'black'
# 验证结果
print(kidshair['allkids']['child3']['hair']) # 输出:black

方案2:原生字典无自定义类实现

如果不想自定义任何类,仅用原生Python能力完成单次路径赋值,不需要额外定义函数,可以用内置的functools.reduce实现:

from functools import reduce

my_dict = {'allkids':{'child1':{'hair':'blonde'},
                      'child2':{'hair':'black'},
                      'child3':{'hair':'red'},
                      'child4':{'hair':'brown'}}}
mypath = ('allkids', 'child3', 'hair')

# 一行完成路径赋值,无需自定义函数
reduce(lambda d, k: d[k], mypath[:-1], my_dict)[mypath[-1]] = 'black'

# 验证结果
print(my_dict['allkids']['child3']['hair']) # 输出:black

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:45:08