Junior — Middle
Can a tuple be used as a key in a dictionary in Python?
sobes.tech AI
Answer from AI
Yes, in Python, tuples can be used as keys in dictionaries if they are immutable. Tuples containing only immutable objects (such as numbers, strings, other tuples) are hashable and can be used as keys.
Example:
my_dict = { (1, 2): "value", (3, 4): "another value" }
print(my_dict[(1, 2)]) # Will output 'value'
However, if a tuple contains mutable objects, such as lists, it cannot be used as a key because it is not hashable.