Sub topic 11
Nested dictionaries and shallow versus deep copies
This chapter assumes you can read and change a dictionary and that you know the difference between mutable and immutable objects. It covers how to work with dictionaries inside dictionaries, and why copying them needs care.
Nested dictionaries
A dictionary value can be any object, including another dictionary or a list. Nesting is how you represent structured data such as configuration files or JSON responses.
config = {
"db": {"host": "localhost", "port": 5432},
"debug": False,
}
print(config["db"]["port"]) # 5432
config["db"]["port"] = 5433 # change an inner value
print(config["db"]) # {'host': 'localhost', 'port': 5433}Each [] step looks up one level. If any level is missing, you get a KeyError.
Reading and writing safely
Chain get() calls with an empty dictionary as the default, so a missing level does not raise an error. To create a missing level before writing to it, use setdefault().
config = {"db": {"host": "localhost"}}
print(config.get("cache", {}).get("ttl", 60)) # 60
config.setdefault("cache", {})["ttl"] = 30
print(config) # {'db': {'host': 'localhost'}, 'cache': {'ttl': 30}}setdefault(key, default) returns the existing value if the key is present. Otherwise it stores the default and returns it.
Assignment does not copy
Writing b = a makes a second name for the same dictionary. A change through either name is visible through both.
a = {"x": 1}
b = a
b["x"] = 99
print(a) # {'x': 99}
print(a is b) # TrueShallow copies
A shallow copy creates a new outer dictionary, but its values are the same objects as in the original. You can make one with d.copy(), dict(d) or {**d}.
For flat dictionaries of immutable values this is enough. With nested mutable values it is not, because both dictionaries point to the same inner object.
import copy
original = {"tags": ["x"]}
shallow = original.copy()
shallow["tags"].append("y")
print(original["tags"]) # ['x', 'y']
deep = copy.deepcopy(original)
deep["tags"].append("z")
print(original["tags"]) # ['x', 'y']Rebinding a key in the shallow copy, such as shallow["tags"] = ["new"], does not affect the original. Only changes made in place to a shared inner object leak through.
Deep copies
copy.deepcopy() walks the structure and duplicates every nested object. Changes to the copy cannot reach the original. It handles objects that refer to themselves, but it is slower and uses more memory, so use it only when you need full independence.
| Method | Outer dict | Inner mutable objects | Typical use |
|---|---|---|---|
| `b = a` | Shared | Shared | Another name for the same data |
| `a.copy()`, `dict(a)`, `{**a}` | New | Shared | Flat dictionaries, or when sharing is intended |
| `copy.deepcopy(a)` | New | New | Nested data you will modify independently |
Choosing a copy
Ask whether you will change anything below the top level.
- If you only add, remove or rebind top-level keys, a shallow copy is enough.
- If you change nested lists or dictionaries in place, use
copy.deepcopy(). - If only one branch changes, you can copy just that branch, for example
new = {**old, "db": {**old["db"], "port": 1}}. This leaves the rest shared and is cheaper than a full deep copy.
Exercise
Given a = {"user": {"name": "Ada"}, "n": 1} and b = a.copy(), what do a["user"]["name"] and a["n"] show after running b["user"]["name"] = "Bob" and b["n"] = 2? How would you change the code so that a is never affected?
Show answer
a["user"]["name"] is "Bob" and a["n"] is still 1. The user value is a dictionary shared by both copies, so the in-place change shows through. The n assignment rebinds a key in b only. To protect a, create b with copy.deepcopy(a) instead of a.copy().