简体   繁体   中英

Issue with Nested Dictionaries in Python

I have some dictionary a.

a = {1: 'a', 2: 'b'}

And I had some dictionary b with a as a value

b = {1: a}

If I print b, change a then print b again, for example:

print(b)
a[1] = 'd'
print(b)

I get the following:

{'a': {1: 'a', 2: 'b'}}
{'a': {1: 'd', 2: 'b'}}

Why does this happen? Does the dict automatically update if you set a value to a variable and then update it? Thanks.

If you write,

b = {1: a}

the value of 1, that is a , refers to the dictionary that you previously defined. So whatever change that you make to dictionary a will be reflected in dictionary b . The literal a in dictionary b is just a reference object to dictionary a .

a , a dict, holds reference to the dictionary {1: 'a', 2: 'b'} . any changes that you make reflect in the dictionary.

since everything in python is an object, implies that every variable is just a reference.

Hence due to the change in dict after the first print(b) the second print(b) is different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM