Why must Python dictionary keys be immutable?
Python Dictionary key must be immutable, why?
Note: If you are looking for a Full Stack Developer (Django+React), then connect with me on LinkedIn or contact me through my portfolio.
Python dictionary keys must always be immutable, which means you can not update the dictionary
key in runtime.
But the Questions is Why Python dictionary
keys should always be immutable ?
Let’s see:
Let’s run the below code and understand its output:
mydict = { [1, 2]: '12' }
print(mydict[[1, 2]])
# Output: TypeError: unhashable type: 'list'
So the output is an Exception
, What does it mean by unhashable
?
It simply means that the Python interpreter is not able to generate a hash for the key given in the dictionary
, whose data type is a list
.
Why Python is generating a Hash for the dictionary
key?
As per the design implementation of Python dictionary
, Python dictionaries are saved in the memory using hash tables.
And In most versions of hash tables, there is no way of changing the key of an entry. This is because the key's hash value is very important, changing the key almost always changes the hash value.
If the key were a mutable object, its value could change, and thus its hash could also change
Then, why python was not generating the hash for a list
, used in a dictionary
as a key?
Because Python list
is a mutable data type, which means it can be modified during runtime, that's why it is not used as a key in a dictionary
.
Imagine if we can change the list
(dictionary key) in runtime, and if dictionary
key changes then how can you retrieve its values because its hash value is not valid now.
So what can we use as a key in a Python dictionary
?
We can use string
, number
, tuple
as a key in Python dictionary
because it can not be modified.
For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.
Social Links
LinkedIn: https://www.linkedin.com/in/mnamegaurav/
Website: https://gaurav.devjunction.in/
GitHub: https://github.com/mnamegaurav
Instagram: https://www.instagram.com/mnamegaurav/
Twitter: https://twitter.com/mnamegaurav