Sobes.tech
Junior — Middle

What are the consequences of using a list as a key in a dictionary?

sobes.tech AI

Answer from AI

In Python, dictionary keys must be hashable (immutable). Lists are mutable data types, so they are not hashable and cannot be used as keys. If you try to use a list as a key, a TypeError: unhashable type: 'list' will be raised.

Example:

my_dict = {}
key = [1, 2, 3]
my_dict[key] = "value"  # TypeError

To use a composite key, you can apply a tuple, which is immutable and hashable:

my_dict = {}
key = (1, 2, 3)
my_dict[key] = "value"  # Works correctly