Show the three Python dictionary views in use and how to convert them into lists.
A dictionary exposes three views over its contents: keys, values and items.
scores = {"ada": 99, "alan": 91}
print(list(scores.keys())) # ['ada', 'alan']
print(list(scores.values())) # [99, 91]
print(list(scores.items())) # [('ada', 99), ('alan', 91)]
# Views are live - they reflect later changes
view = scores.keys()
scores["grace"] = 87
print(list(view)) # ['ada', 'alan', 'grace']Each method returns a view object rather than a list, and the last block shows the difference that matters: the view was taken before grace was added, yet listing it afterwards includes grace. A view is a window onto the dictionary, not a snapshot.
That behaviour is useful — you can hold a view and keep iterating it — but it also has a consequence. Modifying the dictionary's size while you are iterating over a view raises a RuntimeError telling you the dictionary changed size during iteration. Assigning to an existing key is fine, because the size does not change; adding or removing a key is not.
Wrapping a view in list() takes a snapshot, which is what you want when you need to iterate over the keys and modify the dictionary inside the loop.
Another detail worth knowing is that the values view is not unique — two keys can hold the same value, so list(scores.values()) may contain duplicates even though the keys are unique. If you want the distinct values, use a set: set(scores.values()).