Sobes.tech
Senior

What cannot be a key in a Python dictionary?

sobes.tech AI

Answer from AI

In Python, a dictionary key can only be an immutable (hashable) object. This means that a key cannot be a mutable data type, such as a list (list), dictionary (dict), set (set), or other mutable objects.

Examples of permissible keys: numbers, strings, tuples (if all elements of the tuple are also hashable).

Example:

# Valid key
my_dict = {(1, 2): "value"}

# Invalid key - list
my_dict = {[1, 2]: "value"}  # will raise TypeError

Thus, a key cannot be an object that does not support hashing and can be modified after creation.