What data types can you use in a dictionary?
There are two different answers, one for the keys and one for the values of a dictionary
Values can be any type you want
But there are some limitations for keys
In the example in the previous post, you can see two similar dictionaries. They represent the positions in a kitchen unit that has a grid of shelves, so we refer to them using a pair of coordinates…
You can use a tuple of coordinates as a key, but you cannot use a list
The error shows that a list is an 'unhashable type`
A key difference between tuples and lists is that tuples are immutable whereas lists are mutable
The concepts of 'immutability' and 'hashability' are closely linked, but they're not the same
An object is hashable if the same object can always be converted to the same unique identifier during the lifetime of a program
This unique identifier is the hash value which is returned by the `__hash__()` special method
An object must also have `__eq__()` defined to be hashable so that objects can be compared to each other for equality
Any object that meets these requirements can be used as a key in a dictionary
This usually means that immutable types can be used as keys in a dictionary
But what about if we have this tuple:
(2, [3, 5])
The tuple itself is immutable, but one of its elements, the list, is mutable
This means that you cannot change which list is in the second place in the tuple, but you can still change the elements in that list
This means that `(2, [3, 5])` is not hashable
I may write a full long-form article about this topic since there's more to say than can fit in a few posts…