Python tutorials > Data Structures > Tuples > Can tuples be dictionary keys?
Can tuples be dictionary keys?
Basic Example: Using Tuples as Dictionary Keys
my_dict = {
(1, 2): 'value_1',
(3, 4): 'value_2',
(5, 6): 'value_3'
}
print(my_dict[(1, 2)]) # Output: value_1
print(my_dict[(3, 4)]) # Output: value_2
Concepts Behind the Snippet
Real-Life Use Case Section
coordinate_dict = {
(0, 0): 'Origin',
(1, 0): 'X-axis point',
(0, 1): 'Y-axis point',
(1, 1): 'Quadrant I'
}
def get_location_description(x, y):
try:
return coordinate_dict[(x, y)]
except KeyError:
return 'Location Unknown'
print(get_location_description(0, 0)) # Output: Origin
print(get_location_description(1, 1)) # Output: Quadrant I
print(get_location_description(2, 2)) # Output: Location Unknown
Best Practices
Interview Tip
When to use them
Memory Footprint
Alternatives
frozenset
. A frozenset is an immutable version of a set and can be used as a dictionary key.__hash__
and __eq__
methods to define your own hashable objects. This gives you the most flexibility but also requires more code.
Pros
Cons
FAQ
-
Why can't I use a list as a dictionary key?
Lists are mutable, meaning their contents can be changed after creation. Dictionaries require keys to be immutable so their hash values remain constant. If a list's content changed, its hash would also change, making it impossible for the dictionary to reliably find the correct value. -
Can a tuple contain a list, and still be used as a dictionary key?
No. If a tuple contains a mutable object, like a list, then the tuple is effectively mutable and cannot be used as a dictionary key. The dictionary relies on the hash of the key to remain constant. -
Are there performance differences between using tuples and strings as dictionary keys?
In most cases, the performance difference is negligible. Both tuples and strings are efficient for dictionary lookups. However, strings might be slightly faster for very large dictionaries, especially if the strings are interned.