Sobes.tech
Junior — Middle

Can a list be used as a key in a Python dictionary?

sobes.tech AI

Answer from AI

In Python, a list (list) cannot be used as a dictionary key because it is mutable and not a hashable object. Dictionary keys must be immutable and hashable (e.g., strings, numbers, tuples with immutable elements).

If you need to use a sequence as a key, you can use a tuple, which is immutable and hashable:

my_dict = {}
key = (1, 2, 3)  # tuple
my_dict[key] = "value"
print(my_dict[(1, 2, 3)])  # outputs "value"

Attempting to use a list will cause an error:

my_dict = {}
key = [1, 2, 3]
my_dict[key] = "value"  # TypeError: unhashable type: 'list'