In Python, dictionary keys must be of an immutable data type. Mutable objects, which can be modified after creation, cannot be used as keys in a dictionary. This restriction is in place to ensure that the keys remain stable and do not change during the lifetime of the dictionary.
Common immutable data types that can be used as keys include:
- Strings: e.g., 'name', 'age'
- Integers: e.g., 1, 42
- Tuples: e.g., ('apple', 'orange')
On the other hand, lists, sets, and dictionaries are examples of mutable data types and cannot be used as keys:
# Example with a mutable object as a key (this will raise an error)
my_dict = {[1, 2]: 'value'}
Attempting to use a mutable object as a key will result in a TypeError because dictionaries require keys to be hashable and immutable.
If you need to use a collection of mutable objects as a key-like structure, consider using tuples as keys. You can use tuples to represent a fixed sequence of mutable objects and use that tuple as a key in your dictionary. Keep in mind that the order of elements in the tuple matters for uniqueness, as tuples with different orders will be treated as different keys.