Syntax error Why must dictionary keys be immutable in Python?

Why must dictionary keys be immutable in Python?



To understand why dictionary keys must be immutable. Let us related it to hash table. The hash table implementation of dictionaries uses a hash value calculated from the key value to find the key. If let's say the key was a mutable object, its value could change, and thus its hash could also change.

As stated above, since whoever changes the key object can't tell that it was being used as a dictionary key, it can't move the entry around in the dictionary. Then,

  • When you try to look up the same object in the dictionary it won't be found because its hash value is different.

  • If you tried to look up the old value it wouldn't be found either, because the value of the object found in that hash bin would be different.

If you want a dictionary indexed with a list, follow these steps ?

  • Convert the list to a tuple first
  • The function tuple(myList) creates a tuple with the same entries as the list myList.
  • Tuples are immutable and can therefore be used as dictionary keys.

Convert List to Tuple

Example

To convert List to Tuple, use the tuple() ?

# Creating a List mylist = ["Jacob", "Harry", "Mark", "Anthony"] # Displaying the List print("List = ",mylist) # Convert List to Tuple res = tuple(mylist) print("Tuple = ",res)

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Tuple =  ('Jacob', 'Harry', 'Mark', 'Anthony')

Tuple as Keys

Example

Now, we will see an example where first we convert list to tuple, then tuple is set as keys ?

# Creating a List mylist = ["Jacob", "Harry", "Mark", "Anthony"] # Displaying the List print("List = ",mylist) # Convert List to Tuple res = tuple(mylist) print("Tuple = ",res) dct = {2:"num","demo":"string"} print("Dictionary = ") print(dct) # Overwrite existing value with a tuple dct[2]=res print("\nUpdated Dictionary (Tuple as Key)...") print(dct)

Output

('List = ', ['Jacob', 'Harry', 'Mark', 'Anthony'])
('Tuple = ', ('Jacob', 'Harry', 'Mark', 'Anthony'))
Dictionary = 
{'demo': 'string', 2: 'num'}

Updated Dictionary (Tuple as Key)...
{'demo': 'string', 2: ('Jacob', 'Harry', 'Mark', 'Anthony')}
Updated on: 2022-09-19T14:25:30+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements