1
a = (1,2)  
b = {a:1}  
print(b[a]) # This gives 1  
a = (1,2,3)  
print(b[a]) # This gives error but b[(1,2)] is working fine

What I understood is python doesn't run garbage collector after a is changed to (1,2,3) as the tuple (1,2,3) is created as a new object and the tuple (1,2) is still being referenced in b.

What I didn't understood is why 'b' doesn't change the key after 'a' is changed

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Arjunsingh
  • 703
  • 9
  • 22

2 Answers2

2

b = {a:1} creates a dictionary with the value of a as a key and 1 as a value. When you assign a value to a, you create a new value, and b retrain the old value as its key.

The following example, using id, may illustrate it:

>>> a = (1,2)
>>> b = {a:1}
>>> id(a)
139681226321288
>>> a = (1,2,3)
>>> id(a)
139681416297520
>>> id(b.keys()[0])
139681226321288
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Integers, floats, strings, tuples in python are immutable. A dictionary would allow only those keys which would be hashable (immutable built-in objects are hashable). As @Mureinik correctly specified the reason behind the cause, I would give you another example where you can mutate the data by the process you followed above.

>>> l = [1,2,3]
>>> b = {'3' : l}
>>> b
{'3': [1, 2, 3]}
>>> l.append(5)
>>> l
[1, 2, 3, 5]
>>> b
{'3': [1, 2, 3, 5]}

But you cannot change the keys of a dictionary as they are hashed (only values can be updated). You either have to delete existing key-value pair or add new pair.

DecoderReloaded
  • 514
  • 4
  • 12
  • Ok...Now I got it. changing the key would require the dictionary to change the hashmap referring to the value which would then make the dictionary take more time. – Arjunsingh Dec 16 '17 at 13:31