liveBook · Manning

Dictionary view object

As explained in Python How-To

A dynamic view object is a dictionary-backed object that exposes derived keys, values, or key-value pairs and automatically reflects changes to the dictionary.

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

How Python How-To covers it

How deep it goes
Explains view types, live updates, list-copy pitfalls, iteration, and identity, without descending into implementation internals.
Examples
Demonstrates urgencies.keys(), values(), and items(), dictionary updates, stale copied lists, and id()-based identity tracking.
What it assumes
Requires basic dictionary key-value access and familiarity with Python method calls and for loops.
What you can do after
Apply them via keys(), values(), and items() to iterate over dictionary data without losing synchronization after updates.
How it connects
Connects dictionary view objects with dictionaries, iteration, subscript notation, get(), and KeyError handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.