Chapter 9 of 15All chapters
Chapter 9 of 15
Dictionaries
Keys mapped to values, and how to read them safely.
Reading and writing
A dict maps keys to values: scores = {"ada": 10}. Square brackets read a key and raise KeyError when it is missing, while get returns None or a default you supply.
- scores.get("nobody") is None, and scores.get("nobody", 0) is 0.
- The expression "ada" in scores checks for a key without reading the value.
Looping
Looping a dict gives its keys. Use .items() to get key and value together, and .values() when the keys do not matter. Since Python 3.7 the order is the order you inserted.