Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why must dictionary keys be immutable in Python?
Dictionary keys in Python must be immutable because dictionaries are implemented using hash tables. The hash table uses a hash value calculated from the key to quickly locate the key-value pair. If a key were mutable, its value could change after being added to the dictionary, which would also change its hash value.
This creates a fundamental problem: when the key object changes, it can't notify the dictionary that it was being used as a key. This leads to two critical issues ?
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 try to look up the old value, it wouldn't be found either, because the object found in that hash bin would have a different value.
Valid Immutable Key Types
Common immutable types that can be used as dictionary keys include ?
-
Strings:
"key" -
Numbers:
42,3.14 -
Tuples:
(1, 2, 3)(only if all elements are immutable) -
Frozen sets:
frozenset([1, 2, 3])
Demonstrating the Hash Problem
# Immutable keys work fine
my_dict = {
"name": "John",
42: "answer",
(1, 2): "coordinate"
}
print("Dictionary with immutable keys:", my_dict)
# This would cause TypeError if uncommented:
# my_dict[[1, 2, 3]] = "list_key" # Error: unhashable type: 'list'
Dictionary with immutable keys: {'name': 'John', 42: 'answer', (1, 2): 'coordinate'}
Converting List to Tuple for Dictionary Keys
If you need to use a list-like structure as a key, convert it to a tuple first ?
# Creating a list that we want to use as a key
names = ["Jacob", "Harry", "Mark", "Anthony"]
print("Original list:", names)
# Convert list to tuple to make it hashable
tuple_key = tuple(names)
print("Converted tuple:", tuple_key)
# Use tuple as dictionary key
student_grades = {
tuple_key: "Team A",
("Alice", "Bob"): "Team B"
}
print("Dictionary with tuple keys:", student_grades)
Original list: ['Jacob', 'Harry', 'Mark', 'Anthony']
Converted tuple: ('Jacob', 'Harry', 'Mark', 'Anthony')
Dictionary with tuple keys: {('Jacob', 'Harry', 'Mark', 'Anthony'): 'Team A', ('Alice', 'Bob'): 'Team B'}
Practical Example: Coordinate System
# Using tuples as keys for a coordinate system
grid = {}
# Add some coordinates
coordinates = [(0, 0), (1, 1), (2, 3)]
values = ["start", "middle", "end"]
for coord, value in zip(coordinates, values):
grid[coord] = value
print("Grid mapping:", grid)
# Access by coordinate
print("Value at (1, 1):", grid[(1, 1)])
Grid mapping: {(0, 0): 'start', (1, 1): 'middle', (2, 3): 'end'}
Value at (1, 1): middle
Conclusion
Dictionary keys must be immutable because dictionaries use hash tables for fast lookups. Mutable keys would break this system by changing their hash values. Use tuples instead of lists when you need sequence-like dictionary keys.
