Junior — Middle
Is it possible to use a tuple as a key in a Python dictionary?
sobes.tech AI
Answer from AI
Yes, a tuple can be used as a key in a Python dictionary if it consists of immutable (hashable) elements. Dictionary keys must be hashable objects, and tuples are hashable if all their elements are also hashable.
Example:
my_dict = {('a', 1): 'value1', (2, 3): 'value2'}
print(my_dict[('a', 1)]) # Outputs: value1
If the tuple contains mutable objects, such as a list, then such a tuple cannot be used as a key — it will result in a TypeError.