Sobes.tech
Junior — Middle

Is it possible to use a tuple as a key in a Python dictionary, and under what conditions is this allowed?

sobes.tech AI

Answer from AI

Yes, in Python, a tuple can be used as a dictionary key if it is immutable. Dictionary keys must be hashable, meaning they have an immutable state and implement the __hash__ method.

Tuples are inherently immutable, so they are suitable as keys if all their elements are also hashable. For example:

my_dict = { (1, 2): "value", ("a", "b"): 42 }
print(my_dict[(1, 2)])  # Outputs: value

However, if a tuple contains mutable objects, such as lists, it will not be hashable and cannot be used as a key:

key = (1, [2, 3])  # List inside the tuple
my_dict = {}
my_dict[key] = "test"  # Error: TypeError: unhashable type: 'list'

In summary, a tuple can be used as a dictionary key if it consists only of hashable elements.