What can be a key
Strings and numbers work as keys. Not every value does, and the reason is the hash.
A key must keep its hash, and equal keys must hash equal
{[1, 2]: "x"}
TypeError: unhashable type: 'list'
A list can't be a key. A tuple with the same items can:
print({(1, 2): "x"})
{(1, 2): 'x'}
A hash table finds a key in three steps. Each step leans on a promise:
Python's glossary states both promises. A key's hash never changes during its lifetime. And keys that compare equal have the same hash.
Python's immutable built-ins keep both. So ints, floats, strings, bytes, frozensets, and tuples of hashable things can all be keys. Mutable containers, like lists, sets and dicts, can't.
Equal keys are one key, even across types:
print({1: "int", 1.0: "float", True: "bool"})
{1: 'bool'}
1, 1.0 and True compare equal, so Python promises they hash equal. The dict treats them as one key:
| Write | The dict after it |
|---|---|
1: "int" | {1: 'int'} |
1.0: "float" | {1: 'float'}: 1.0 == 1, the same key, a new value |
True: "bool" | {1: 'bool'}: True == 1, the same key, a new value |
The first spelling of the key stays, and the last value wins.
To catch an error instead of stopping, put the call in a try block and name the error in except:
try:
hash([1, 2])
print("hashable")
except TypeError:
print("not hashable")
not hashable
The try block runs until a line raises. If the error is the one the except line names, Python runs that block and carries on.
In the editor, write can_be_key(value): True when hash(value) works, and False when it raises TypeError. Then write distinct_keys(values): how many keys a dict holds once each value goes in as a key, where equal values like 1 and 1.0 share one key.