Skip to main content
 首页 » 编程设计

python之字典值是另一个字典

2024年10月24日22小虾米

<分区>

考虑一下

dict1={} 
dict2={} 
dict2["first_d2"]="Yes" 
dict1["first_d1"]=dict2 
print dict1 
print dict2 
dict2={} 
print dict1      ===>Here's the doubt 
print dict2 

输出:

{'first_d1': {'first_d2': 'Yes'}} 
{'first_d2': 'Yes'} 
{'first_d1': {'first_d2': 'Yes'}}   ===>Why is this not resetting?Its referencing to dict2 
{} 

现在 python 字典是可变的。所以 dict1 正在引用 dict2。现在在第一次操作 dict2 被重置后,为什么值是dict1 没有重置?

根据我的理解,可变对象会更改内存中的内容并且不会返回新对象。那么为什么这里没有发生这种情况呢?我错过了什么?

从可变和不可变的角度我很困惑!