Dictionary Views, Sorting and Merging
15 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Modern Python provides powerful features for querying, transforming, and merging dictionaries. Dictionary views reflect real-time changes to the underlying data, key views support mathematical set operations, and Python 3.9 introduced the intuitive dictionary merge operator |.
Dynamic Dictionary Views
Dictionary view is a live window onto a dictionary's keys, values or items. It changes when the dictionary changes and copies nothing.
In Python 3, .keys(), .values(), and .items() return dynamic view objects rather than static lists.
scores = {"Aarav": 90, "Diya": 95}keys_view = scores.keys()print("Before:", keys_view)
scores["Kavya"] = 88print("After: ", keys_view) # Reflects Kavya automatically!Example 1 · A view follows the dictionary
stock = {"pen": 40, "book": 12}items = stock.items()stock["bag"] = 5del stock["pen"]print(list(items))[('book', 12), ('bag', 5)]What this code does
itemswas created once, before the two changes.- It still shows the current state, because a view copies nothing.
Views consume O(1) memory because they reference the underlying dictionary directly.
Set Operations on Dictionary Keys
Key view is the object returned by d.keys(). It behaves like a set, so you can use &, | and - on it.
Dictionary .keys() views behave like set objects, supporting set union, intersection, and difference directly!
d1 = {"a": 1, "b": 2, "c": 3}d2 = {"b": 20, "c": 30, "d": 40}
# Intersection: keys present in bothcommon_keys = d1.keys() & d2.keys() # {'b', 'c'}
# Difference: keys in d1 but not d2unique_to_d1 = d1.keys() - d2.keys() # {'a'}This eliminates the need to explicitly convert keys to set(d.keys()).
Sorting Dictionaries by Value
Key function is a function passed as key= to sorted(). It returns the value that sorted() should compare for each item.
Use sorted() on .items(), passing a lambda function extracting index 1 (the value).
inventory = {"apples": 50, "bananas": 12, "oranges": 34}# Sort ascending by quantitysorted_items = sorted(inventory.items(), key=lambda kv: kv[1])print("Sorted:", sorted_items)
# Reconstruct sorted dictionarysorted_dict = dict(sorted_items)print("Sorted dict:", sorted_dict)Example 2 · Top products by sales
sales = {"laptop": 120, "phone": 340, "tablet": 90, "watch": 210}ranked = sorted(sales.items(), key=lambda kv: kv[1], reverse=True)for name, units in ranked[:2]: print(f"{name}: {units}")phone: 340 watch: 210
What this code does
kv[1]is the sales number, so the largest comes first.- Slicing
[:2]keeps the top two of the sorted list.
dict(sorted_items) keeps that order, because dictionaries remember insertion order. New keys added later go at the end. Sorting costs O(N log N).
Dictionary Merge Operators (| and |=)
Union operator is the | symbol on two dictionaries. It builds a new dictionary, and the right side wins when keys repeat.
Introduced in PEP 584 (Python 3.9), the | operator cleanly merges two dictionaries.
defaults = {"theme": "light", "notifications": True}user_pref = {"theme": "dark"}
# Merge: right operand takes precedence on conflictsconfig = defaults | user_prefprint(config) # {'theme': 'dark', 'notifications': True}Example 3 · Shared members and merged scores
team_a = {"Aarav": 10, "Bhavna": 20}team_b = {"Bhavna": 25, "Chetan": 30}
# Keys in both teamsshared = team_a.keys() & team_b.keys()# Merged roster (team_b overrides conflicts)merged = team_a | team_b
print("Shared members:", sorted(list(shared)))print("Merged Bhavna score:", merged["Bhavna"])Shared members: ['Bhavna'] Merged Bhavna score: 25
What this code does
team_a.keys() & team_b.keys()computes common keys.team_a | team_bmerges with right-side precedence (25overrides20).
Use d1 |= d2 for in-place updating.
Comparing two snapshots
Key views make a change report short: added, removed and changed keys come from set operations. View creation is O(1); each operation here is O(N).
old = {"theme": "light", "timeout": 30, "retries": 3}new = {"theme": "dark", "timeout": 30, "debug": True}
added = new.keys() - old.keys()removed = old.keys() - new.keys()changed = {k for k in old.keys() & new.keys() if old[k] != new[k]}print(sorted(added), sorted(removed), sorted(changed))Example 4 · Price list changes
yesterday = {"A": 100, "B": 250, "C": 80}today = {"A": 100, "B": 260, "D": 40}print("new:", sorted(today.keys() - yesterday.keys()))print("gone:", sorted(yesterday.keys() - today.keys()))print("changed:", sorted(today.items() - yesterday.items()))new: ['D']
gone: ['C']
changed: [('B', 260), ('D', 40)]What this code does
- Key views give new and removed products.
items()views are set-like when the values are hashable, so subtracting finds changed pairs.
Checking key in d.keys() is O(1), but value in d.values() scans every value in O(N), so keep lookups on the keys.
What's next
You finished the preview of Built-in Sequences & Mappings
Python Programming has 21 sections, 110 modules and 609 lessons. An account opens every lesson and saves your progress.
Next step
Check your understanding
11 quick questions