简体   繁体   中英

Immutability of dictionary keys in python

dic={}
dic[1]=100
dic[2]=200
dic[1]+=500

here I have initialed a dictionary and I am able to update the key value of the dictionary. But keys in dictionary are immutable, so what's actually happening, can someone please tell?

Just think of it this way. We have an empty dictionary:

d = {}

If we do this:

d[1] = 100

we are simply adding a key and assigning a value to that key, right then and there.


Just like sets, dicts cannot have duplicate keys, so adding another key with the same name will overwrite the original.

Like doing calling d[1] = 200 will overwrite the original d[1] .

d[1] += 500 is the same as:

d[1] = d[1]+500

where we are simply telling python to add a key to d called 1 , and assign the value of the original key plus 500 to that key.

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