Can a tuple be used as a dictionary key?


#1

Question

This exercise says a key can be a hashable type like a number or string. Can a tuple be used as a dictionary key?

Answer

Yes, a tuple is a hashable value and can be used as a dictionary key. A tuple would be useful as a key when storing values associated with a grid or some other coordinate type system. The following code example shows a dictionary with keys representing a simple x,y grid system.

coordinates = { (0,0) : 100, (1,1) : 200}
coordinates[(1,0)] = 150
coordinates[(0,1)] = 125

print(coordinates)
# {(0, 0): 100, (1, 1): 200, (1, 0): 150, (0, 1): 125}