首页 > 解决方案 > 是否可以在 python 中为 dict 行设置别名?

问题描述

我认为答案是否定的,但想问后代:-)

今天我在我的代码库中发现了有趣的错误。

这是一些上下文:

>>> d1={1:[1], 2:[2], 3:[3]}    ### in practice I have more complex data but [] is correct
>>> a1=d1[2]                    ### I wanted to use a1 as alias, in 15x places 
>>> id(d1)
4503224000
>>> id(a1)
4504750528
>>> id(d1[2])
4504750528
>>> d1
{1: [1], 2: [2], 3: [3]}
>>> a1
[2]
>>> a1[0] = 22                  ### this also correct, I know it is hack
>>> d1                          ### value is original dict is changed
{1: [1], 2: [22], 3: [3]}
>>> a1                  
[22]
>>> del a1                      ### now I want to delete it 
>>> a1                          ### it is deleted 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a1' is not defined
>>> d1                          ### but not in original dict
{1: [1], 2: [22], 3: [3]}
>>> del d1[2]                   ### must be deleted directly 
>>> d1
{1: [1], 3: [3]}

我了解正在发生的事情以及原因。

但我很好奇有没有办法将 a1 作为原始 d1[2] 的别名,所以当 del a1 完成时它与 del d1[2] 相同?

PS 我有这个想法是因为我受到 C/C++ 的不良影响。

标签: pythondictionary

解决方案


推荐阅读