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

Python中如何缩写深度嵌套字典的访问路径并修改原字典

当然可行!利用Python的引用特性轻松简化嵌套字典操作

核心原理:字典是可变对象,赋值传递引用

在Python里,像字典、列表这类可变对象,当你把它们赋值给另一个变量时,并没有复制整个对象,只是把新变量指向了原对象在内存中的地址。也就是说,新变量和原字典的深层子字典其实是同一个东西,修改新变量的内容自然会同步到原字典里。

具体实现步骤

  1. 先把深层子字典绑定到缩写变量
    先执行这行代码,把你要频繁操作的深层子字典赋值给nested_child_info:
    nested_child_info = master_dictionary['sub_categories'][sub_cat_name]['attributes'][attribute_name]['special_type']['nested_children'][child_cat_name]
    
  2. 用缩写变量直接操作
    之后你就可以用简化的路径修改内容,这会直接影响原字典:
    nested_child_info[color] = "blue"
    

实际例子验证效果

咱们写个小demo确认一下:

# 构造深度嵌套的原字典
master_dictionary = {
    'sub_categories': {
        'electronics': {
            'attributes': {
                'screen': {
                    'special_type': {
                        'nested_children': {
                            'lcd': {}
                        }
                    }
                }
            }
        }
    }
}

# 定义变量对应路径中的键
sub_cat_name = 'electronics'
attribute_name = 'screen'
child_cat_name = 'lcd'
color = 'display_color'

# 绑定缩写变量
nested_child_info = master_dictionary['sub_categories'][sub_cat_name]['attributes'][attribute_name]['special_type']['nested_children'][child_cat_name]

# 修改缩写变量
nested_child_info[color] = "blue"

# 查看原字典的变化
print(master_dictionary['sub_categories'][sub_cat_name]['attributes'][attribute_name]['special_type']['nested_children'][child_cat_name][color])
# 输出: blue

可以看到,原字典里的对应值确实被修改了。

注意事项

  • 这个方法只适用于可变对象(字典、列表等),如果是字符串、数字这类不可变对象,赋值后修改不会影响原对象(因为不可变对象修改时会创建新对象)。
  • 如果之后你重新给nested_child_info赋值一个新字典(比如nested_child_info = {}),那它就和原字典断开联系了,再修改就不会影响原字典。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:33:56