Junior — Middle
Can a tuple be used as a key for a dictionary in Python?
sobes.tech AI
Answer from AI
Yes, in Python, tuples can be used as dictionary keys if they contain only immutable (hashable) objects. A dictionary key must be hashable, meaning it has an immutable type and implements the __hash__ method. For example, a tuple of numbers or strings is suitable, but a tuple containing a list is not.
Example:
my_dict = { (1, 2): "value", ("a", "b"): 42 }
print(my_dict[(1, 2)]) # Outputs: value
Trying to use a tuple with a mutable element, such as a list, will result in an error:
my_dict = { (1, [2, 3]): "value" } # TypeError: unhashable type: 'list'