Python Basics: Working with Live Dictionary Views
Dictionary keys, values, and items can be inspected through live views. Understanding the difference between a view and a snapshot helps when comparing mappings or removing selected entries.
These three standalone examples were tested on Linux with Python 3.12.14. They require no third-party packages. Assertions check the results; run without Python’s -O option.
Prepare a scratch directory
You need Bash, Python 3.12 or newer on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. Keep using the same terminal and save each named source file as UTF-8.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 11. Keep a live view and a snapshot
Save as observe_dictionary_views.py:
stock = {"tea": 2, "coffee": 1}
names = stock.keys()
quantities = stock.values()
entries = stock.items()
snapshot = list(entries)
stock["tea"] = 3
stock["cocoa"] = 4
assert list(names) == ["tea", "coffee", "cocoa"]
assert list(quantities) == [3, 1, 4]
assert snapshot == [("tea", 2), ("coffee", 1)]
print("Names:", list(names))
print("Quantities:", list(quantities))
print("Live entries:", list(entries))
print("Snapshot:", snapshot)Run it:
python3 observe_dictionary_views.pyOutput:
Names: ['tea', 'coffee', 'cocoa']
Quantities: [3, 1, 4]
Live entries: [('tea', 3), ('coffee', 1), ('cocoa', 4)]
Snapshot: [('tea', 2), ('coffee', 1)]keys(), values(), and items() reflect later changes to the dictionary. list(entries) captures the pairs present at that moment. Traversal follows insertion order. This snapshot contains integers; a snapshot containing mutable values would still reference those same objects.
2. Compare the keys in two mappings
Save as compare_dictionary_keys.py:
previous = {"api": 1, "worker": 2}
current = {"api": 3, "cache": 1}
added = current.keys() - previous.keys()
removed = previous.keys() - current.keys()
shared = previous.keys() & current.keys()
assert added == {"cache"}
assert removed == {"worker"}
assert shared == {"api"}
print("Added:", sorted(added))
print("Removed:", sorted(removed))
print("Shared:", sorted(shared))
print("Shared value changed:", previous["api"] != current["api"])Run it:
python3 compare_dictionary_keys.pyOutput:
Added: ['cache']
Removed: ['worker']
Shared: ['api']
Shared value changed: TrueKey views support set-style comparison. These expressions return sets, so sorting the string keys makes the report deterministic. A shared key can still have a changed value; the comparison of keys alone cannot detect that.
3. Remove entries while iterating over a snapshot
Save as prune_empty_stock.py:
stock = {"tea": 0, "coffee": 3, "cocoa": 0}
names = stock.keys()
removed = []
for name, quantity in list(stock.items()):
if quantity == 0:
del stock[name]
removed.append(name)
assert stock == {"coffee": 3}
assert list(names) == ["coffee"]
print("Removed:", removed)
print("Remaining:", stock)
print("Existing view:", list(names))Run it:
python3 prune_empty_stock.pyOutput:
Removed: ['tea', 'cocoa']
Remaining: {'coffee': 3}
Existing view: ['coffee']Adding or deleting dictionary entries during live-view iteration is unsafe. Iterating a list of pairs separates this loop from structural changes to stock. The saved keys view still reflects the final dictionary.
When to use this
Use a view for current contents, and a snapshot when this loop must see a fixed collection of entries. Views are not lists: list(view) is an explicit conversion. Values views do not provide the set operations used by key views.
References
Clean up
In the same terminal, remove only these example files, then return to your original directory and remove the empty scratch directory:
rm -- observe_dictionary_views.py compare_dictionary_keys.py prune_empty_stock.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.