dict.items(), .keys(), .values()
These three methods let you walk over a dict's keys, values, or pairs without copying it.
Used in 81 lessons of the course, from 00.01.
A dict stores key: value pairs. To look at them in parts, it has three methods:
.keys()gives the keys..values()gives the values..items()gives(key, value)pairs, as tuples.
Each one returns a view, not a list. A view is a live window onto the dict: if the dict changes, the view shows it. That is why it is cheap to create. If you need a real list, convert it with list(...).
In a for loop, .items() pairs well with unpacking: for k, v in d.items(). That gives you the key and the value their own names.
In the course you will see GLOSSARY.keys() passed to difflib.get_close_matches: the function receives all the keys as the candidates and looks for the ones closest to key.
Reach for it when: you want to loop over a dict, or hand its keys or values to something that expects a collection of items.
Examples
Common mistake
d = {"a": 1, "b": 2}
keys = d.keys()
print(keys[0])Why: A view is not a list, so it does not support indexing like `keys[0]`.
How to write it: Convert it first: list(d.keys())[0], or use next(iter(d)) for the first key.
Common mistake
d = {"a": 1, "b": 2}
for k in d:
if k == "a":
d["c"] = 3Why: Adding keys while you loop over the dict changes its size, and Python stops it.
How to write it: Loop over a copy: for k in list(d):, or build a new dict.
