Middle
Why must keys in a Python dictionary be immutable, and can mutable keys be used?
sobes.tech AI
Answer from AI
Keys in a Python dictionary must be immutable because the dictionary uses hashing for fast access to values. If a key is mutable, its hash may change after being inserted into the dictionary, which will make it impossible to find that key and, consequently, its value.
For example, strings, numbers, and tuples (containing immutable elements) are suitable keys because their hash is constant.
Mutable keys (such as lists or dictionaries) cannot be used because they do not have a constant hash and do not support the hash() method. Attempting to use a mutable object as a key will result in a TypeError.
Example:
my_dict = {}
my_dict[[1, 2, 3]] = "value" # TypeError: unhashable type: 'list'
Thus, the immutability of keys guarantees the correct operation of the dictionary's hash table.