Dictionaries, Part 2: Comprehensions, JSON and Merging
After this lesson, you will be able to:
- Build dictionaries from other data with a comprehension
- Read and write nested dictionaries, the shape JSON arrives in
- Say why dicts keep insertion order, and since when
- Merge dictionaries with | and |=
#Dict Comprehensions
A dict comprehension builds a dictionary from another collection (a list, a range, another dict) in one line.
# Basic comprehension: {key_expr: value_expr for item in iterable}
squares = {n: n**2 for n in range(1, 8)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}
# With a condition
even_squares = {n: n**2 for n in range(1, 11) if n % 2 == 0}
print(even_squares) # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
# Invert a dict (swap keys and values)
word_index = {"cat": 0, "dog": 1, "bird": 2}
index_word = {v: k for k, v in word_index.items()}
print(index_word) # {0: 'cat', 1: 'dog', 2: 'bird'}
# From two parallel lists
keys = ["name", "age", "city"]
values = ["Alice", 30, "London"]
record = {k: v for k, v in zip(keys, values)}
print(record) # {'name': 'Alice', 'age': 30, 'city': 'London'}
# Normalize string keys to lowercase
raw = {"Name": "Bob", "AGE": 42, "City": "Paris"}
normalized = {k.lower(): v for k, v in raw.items()}
print(normalized) # {'name': 'Bob', 'age': 42, 'city': 'Paris'}#Nested Dicts and JSON
Real-world settings files and anything received from another program are almost always nested dicts.
The flatten function below calls itself for each inner dict. That is called recursion, and a later lesson explains it. For now, read it as: walk into each inner dict, and join the key names with dots.
# Building a nested settings object
app_config = {
"editor": {
"theme": "dark",
"font_size": 14,
"tab_width": 4,
},
"backup": {
"enabled": True,
"interval_minutes": 15,
"destination": {
"kind": "folder",
"path": "/backups/daily",
},
},
"language": "en",
}
# Safe nested access with .get()
interval = app_config.get("backup", {}).get("interval_minutes", 30)
path = (app_config.get("backup", {})
.get("destination", {})
.get("path", "/tmp"))
print(f"Every {interval} min -> {path}") # Every 15 min -> /backups/daily
# This pattern is far safer than chained []
# app_config["backup"]["destination"]["missing_key"] # KeyError!
# Flattening a nested dict (useful for logging or saving)
def flatten_dict(d: dict, prefix: str = "", sep: str = ".") -> dict:
"""Recursively flatten a nested dict with dotted keys."""
result = {}
for k, v in d.items():
full_key = f"{prefix}{sep}{k}" if prefix else k
if isinstance(v, dict):
result.update(flatten_dict(v, full_key, sep))
else:
result[full_key] = v
return result
flat = flatten_dict(app_config)
for key, val in flat.items():
print(f" {key}: {val}")
# editor.theme: dark
# editor.font_size: 14
# editor.tab_width: 4
# backup.enabled: True
# backup.interval_minutes: 15
# backup.destination.kind: folder
# backup.destination.path: /backups/daily
# language: en#Dict Ordering (Python 3.7+)
Since Python 3.7, a dict remembers the order in which you added its keys. This is a promise of the Python language itself, not a habit of one version, so you can rely on it.
# Insertion order is preserved
steps = {}
steps["load_data"] = 1
steps["preprocess"] = 2
steps["train_model"] = 3
steps["evaluate"] = 4
steps["save"] = 5
for step, order in steps.items():
print(f" Step {order}: {step}")
# Always prints in insertion order
# Reversing a dict (Python 3.8+)
reversed_steps = dict(reversed(steps.items()))
print(list(reversed_steps.keys()))
# ['save', 'evaluate', 'train_model', 'preprocess', 'load_data']collections.OrderedDict to keep order. That is now rarely needed.Since 3.7 a dict preserves insertion order. Does that make it an ordered collection you can rely on for sorting?
#Dict Merge Operators (Python 3.9+)
| and |= for merging dicts — cleaner than .update() when you want a new dict.defaults = {"timeout": 30, "retries": 3, "debug": False}
overrides = {"timeout": 60, "debug": True}
# | creates a NEW merged dict (right side wins on conflicts)
merged = defaults | overrides
print(merged) # {'timeout': 60, 'retries': 3, 'debug': True}
# Original dicts are unchanged
print(defaults["timeout"]) # 30
# |= updates in-place (like .update())
config = {"env": "prod", "port": 8080}
extra = {"port": 9090, "workers": 4}
config |= extra
print(config) # {'env': 'prod', 'port': 9090, 'workers': 4}
# Useful for layered settings (command-line beats file beats defaults)
defaults = {"font_size": 14, "autosave": True, "theme": "dark"}
from_file = {"font_size": 16}
from_flags = {"autosave": False}
final = defaults | from_file | from_flags
print(final) # {'font_size': 16, 'autosave': False, 'theme': 'dark'}#Interactive Visualization: Hash Table Explorer
Insert keys and watch each one become a hash and land in a bucket. This lab is a simple version called chaining: keys that land in the same bucket share it in a list. CPython uses open addressing instead (part 1), where a taken slot sends the key to another slot.
#Code Playground
Tests: Build a word frequency counter and a safe nested settings reader!
#Key Takeaways
- A dict comprehension builds a mapping in one expression —
{name: len(name) for name in names}replaces the create-empty-dict-then-loop pattern, and adding anifclause filters while it builds. - JSON is dicts inside dicts — reading a nested field means walking one level at a time, and chained
.get()calls with sensible defaults let a missing level return a default instead of raisingKeyError. - Insertion order is a language guarantee since Python 3.7 — iterating a dict returns keys in the order they were added, so you can rely on it rather than reaching for
OrderedDict. - The merge operators arrived in 3.9 —
a | breturns a new merged dict anda |= bupdates in place, and where a key exists in both the RIGHT side wins. That right-wins rule is exactly the shape of applying user settings on top of defaults.
What does the | operator do for dicts in Python 3.9+?
Defaults should be overridden by whatever the user chose. This merge does the opposite — the user asked for 5 retries and gets 3. Fix it.
5
Build a word frequency counter
Write a function `word_count(text)` that takes a string and returns a dict mapping each lowercase word to the number of times it appears. Split on whitespace and ignore case.
>>> word_count("the cat and the dog and the bird")
{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}