Junior — Middle
Can tuples with multiple elements be used as keys in a dictionary?
sobes.tech AI
Answer from AI
Yes, a tuple with multiple elements can be used as a key in a dictionary if all elements of the tuple are immutable (hashable) data types. Tuples themselves are immutable and hashable if their contents are also hashable.
Example:
my_dict = {('a', 1): 'value1', ('b', 2): 'value2'}
print(my_dict[('a', 1)]) # Outputs 'value1'
If the tuple contains mutable objects, such as lists, then such a tuple cannot be used as a key.