A dictionary key is a hashable identifier used to access an associated value. Unlike list indices, keys can be strings, numbers, tuples, or other eligible Python objects. section 7.1 section 7.4
Use dictionary keys according to these rules:
- Assign and retrieve values with bracket notation, such as dictionary[key]. section 7.1
- Choose immutable, hashable objects. Integers, floats, booleans, strings, bytes, frozensets, and suitable tuples can be keys. section 7.4
- Do not use mutable objects such as lists, dictionaries, sets, or bytearrays as keys; tuples containing mutable objects are also invalid. section 7.4
- Keys identify values rather than positions, so dictionary access does not depend on an item's numeric index. section 7.1 section 7.9
Words as keys
A word-counting loop uses each word as a key and updates its associated count: occurrences[word] = occurrences.get(word, 0) + 1. The resulting dictionary maps each distinct word to its frequency. section 7.3
Table 7.2 Python values eligible to be used as dictionary keys (view table figure)
| Python type |
Immutable? |
Hashable? |
Dictionary key? |
|---|---|---|---|
| int |
Yes |
Yes |
Yes |
| float |
Yes |
Yes |
Yes |
| boolean |
Yes |
Yes |
Yes |
| complex |
Yes |
Yes |
Yes |
| str |
Yes |
Yes |
Yes |
| bytes |
Yes |
Yes |
Yes |
| bytearray |
No |
No |
No |
| list |
No |
No |
No |
| tuple |
Yes |
Sometimes |
Sometimes |
| set |
No |
No |
No |
| frozenset |
Yes |
Yes |
Yes |
| dictionary |
No |
No |
No |
Use the eligibility table to compare built-in types by immutability, hashability, and suitability as dictionary keys. section 7.4









