Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions. However, there are a couple restrictions that dictionary keys must abide by.
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn’t make sense to map a particular key more than once. If you specify a key a second time during the initial creation of a dictionary, then the second occurrence will override the first.
Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. Values, on the other hand, can be any type and can be used more than once.
Joshua Dougas on Sept. 23, 2021
I was suprised that the error message for list keys does not mention mutability at all!
I played around and found that mutable objects actually do work as keys, as long as the object is hashable. We can make a descendant list that is hashable by implementing the hash() method using some arbitrary scheme.
I did this below and found that mutable objects do in fact work as dictionary keys, it is just that using mutable keys may lead to unexpected results.
For example if you add a item using a mutable key and then irreversibly change the key, then you risk ‘loosing’ the associated value. I’m sure there are a bunch of other caveats, such as with collisions, as well.