A dictionary view object exposes a dictionary’s keys, values, or key-value pairs without copying them into a separate list. The objects returned by keys(), values(), and items() are dict_keys, dict_values, and dict_items, respectively. section 3.4.1
urgencies = {"Laundry": 3, "Homework": 5, "Museum": 2}
urgen_keys = urgencies.keys()
urgen_values = urgencies.values()
urgen_items = urgencies.items()
print(urgen_keys, urgen_values, urgen_items, sep="\n")
# output the following lines:
dict_keys(['Laundry', 'Homework', 'Museum'])
dict_values([3, 5, 2])
dict_items([('Laundry', 3), ('Homework', 5), ('Museum', 2)])
Inspect the three view types returned from a dictionary and compare their displayed contents. section 3.4.1
Views stay synchronized with their underlying dictionary. Adding, changing, or removing key-value pairs changes what the existing view displays. This makes views safer for tracking dictionary data than a list created from a view, because that list remains unchanged after later updates. section 3.4.1
Use dictionary view objects for these practical patterns:
- Iterate over keys, values, or key-value pairs in a for loop; views are iterable. section 3.4.6
- Choose subscript notation when misspelled keys should raise KeyError during development; use get when a fallback is appropriate. section 3.4.6
- Prefer views when later dictionary changes must be reflected automatically. section 3.4.1
Tracking a view object
Create a dict_keys view, update the dictionary, and inspect both the view’s contents and its identity. The contents should change while the view object’s memory address remains the same. section 3.4.7
