Sub topic 11
Nested Dictionaries and Shallow versus Deep Copies
This chapter assumes you know how to create, read and update dictionaries, and that you understand mutable and immutable objects. It covers dictionaries that hold other dictionaries or lists, and what happens when you copy them.
Why nesting is common
Real data is rarely flat. A user record can hold an address, a list of roles and a set of preferences. In Python, you model this by storing containers as dictionary values.
config = {
"app": {"name": "shop", "debug": False},
"db": {"host": "localhost", "port": 5432},
"admins": ["ana", "ben"],
}
print(config["db"]["port"]) # 5432
print(config["admins"][0]) # anaEach [] step unwraps one level. The expression config["db"]["port"] first fetches the inner dictionary, then looks up "port" in it.
Reading nested values safely
A chain of [] lookups raises KeyError at the first missing key. If the data may be incomplete, chain get() calls and give each step an empty dictionary as the default.
config = {"db": {"host": "localhost"}}
print(config.get("db", {}).get("port", 5432)) # 5432
print(config.get("cache", {}).get("ttl", 60)) # 60This works only while every intermediate value really is a dictionary. If config["db"] were None or a string, the second get() would raise AttributeError. Use this pattern for data whose shape you control, and validate input from outside sources first.
Building and updating nested structures
Assigning into a nested dictionary requires that the inner dictionary already exists. setdefault() and defaultdict create it on demand.
from collections import defaultdict
sales = {}
sales.setdefault("north", {})["apple"] = 10
sales.setdefault("north", {})["pear"] = 4
print(sales) # {'north': {'apple': 10, 'pear': 4}}
totals = defaultdict(lambda: defaultdict(int))
totals["south"]["apple"] += 3
totals["south"]["apple"] += 2
print(totals["south"]["apple"]) # 5defaultdict(lambda: defaultdict(int)) creates a two-level counter. The outer factory makes a fresh inner defaultdict for each new key.
Assignment does not copy
The statement b = a binds a second name to the same dictionary. No new dictionary is created, so a change through one name is visible through the other.
a = {"x": 1}
b = a
b["x"] = 99
print(a) # {'x': 99}
print(a is b) # TrueThis is the first source of surprise. To get an independent dictionary, you have to copy explicitly.
Shallow copies
A shallow copy creates a new outer dictionary and fills it with the same value objects as the original. You can make one with d.copy(), dict(d) or {**d}.
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']After original.copy(), the two dictionaries are separate objects, but original["tags"] and shallow["tags"] refer to one list. Appending through either name changes that single list. Deep copying with copy.deepcopy() duplicates the list as well, so the later append to deep leaves original unchanged.
The distinction depends on what you do:
- Rebinding a key in the copy, such as
shallow["tags"] = [], affects only the copy. It replaces the reference in the copy's own table. - Mutating an object reached through the copy, such as
shallow["tags"].append("y"), affects every dictionary that shares that object.
original = {"tags": ["x"], "count": 1}
shallow = original.copy()
shallow["count"] = 2 # rebinding: original unaffected
shallow["tags"] = ["new"] # rebinding: original unaffected
print(original) # {'tags': ['x'], 'count': 1}
shallow = original.copy()
shallow["tags"].append("y") # mutation of a shared list
print(original) # {'tags': ['x', 'y'], 'count': 1}Immutable values such as numbers, strings and tuples of immutable items are safe to share, because nothing can change them in place.
Deep copies
copy.deepcopy(obj) walks the structure recursively and copies every mutable object it finds. It keeps a memo of objects already copied, which gives two properties worth knowing.
- Shared references inside the original stay shared inside the copy. If two keys point to one list, the copy has two keys pointing to one new list.
- Circular references do not cause infinite recursion.
import copy
shared = [1, 2]
data = {"a": shared, "b": shared}
clone = copy.deepcopy(data)
print(clone["a"] is clone["b"]) # True
print(clone["a"] is shared) # False
loop = {"name": "root"}
loop["self"] = loop
loop_copy = copy.deepcopy(loop)
print(loop_copy["self"] is loop_copy) # TrueCosts and limits of deepcopy
Deep copying is not free. Consider these points before reaching for it.
- Time and memory. It visits every object, so a large structure is expensive to copy. Copying inside a hot loop can dominate your run time.
- Uncopyable objects. Objects such as open files, locks and sockets cannot be copied and raise an error. Custom classes can control copying with
__deepcopy__. - Unintended duplication. Copying a structure that holds a reference to a large shared resource, such as a database client, duplicates it too.
Alternatives often fit better:
| Situation | Better approach |
|---|---|
| Only one level of nesting changes | Copy just that level, for example `{**d, "tags": [*d["tags"], "y"]}` |
| Data is plain JSON-like values | `json.loads(json.dumps(d))` also works, but it converts tuples to lists and fails on non-JSON types |
| You do not need to mutate at all | Treat the data as read-only and build new values instead of editing |
Updating one branch without a full deep copy
When you change a single path in a nested dictionary, copy only the containers along that path. Everything else stays shared, which is safe as long as you never mutate the shared parts.
settings = {
"ui": {"theme": "light", "font": 12},
"db": {"host": "localhost", "port": 5432},
}
updated = {**settings, "ui": {**settings["ui"], "theme": "dark"}}
print(settings["ui"]["theme"]) # light
print(updated["ui"]["theme"]) # dark
print(updated["db"] is settings["db"]) # TrueThe "db" branch is shared between the two dictionaries, while the "ui" branch is fresh. This technique is cheap and makes the change explicit.
A common bug: copying with multiplication or a shared default
Two other patterns create unintended sharing without any explicit copy.
template = {"hits": 0}
rows = [template] * 3
rows[0]["hits"] += 1
print(rows) # [{'hits': 1}, {'hits': 1}, {'hits': 1}]
rows = [dict(template) for _ in range(3)]
rows[0]["hits"] += 1
print(rows) # [{'hits': 1}, {'hits': 0}, {'hits': 0}]The expression [template] * 3 repeats the reference, not the dictionary. A comprehension that builds a new dictionary on each pass fixes it. The same problem appears with dict.fromkeys(keys, []), which assigns one shared list to every key. Use a comprehension such as {k: [] for k in keys} instead.
Choosing a copy strategy
- If you will not mutate either dictionary, no copy is needed.
- If all values are immutable, a shallow copy is enough.
- If you mutate nested containers and the original must stay intact, use
copy.deepcopy(), or copy only the branches you change. - If the structure contains uncopyable objects, define
__deepcopy__or restructure so that such objects live outside the copied data.
Exercise
Given a = {"cfg": {"depth": 1}, "name": "x"} and b = a.copy(), you run b["cfg"]["depth"] = 2 and then b["name"] = "y". What are a["cfg"]["depth"] and a["name"] afterwards, and why?
Show answer
a["cfg"]["depth"] is 2 and a["name"] is "x". The shallow copy shares the inner cfg dictionary, so mutating it through b also changes a. Assigning b["name"] = "y" rebinds a key in b's own table, so a keeps "x".
Exercise
Write a line that creates d with keys "a", "b" and "c", each holding its own empty list, so that d["a"].append(1) does not affect d["b"]. Explain why dict.fromkeys("abc", []) fails to do this.
Show answer
d = {k: [] for k in "abc"}. The dict.fromkeys("abc", []) call evaluates [] once and uses that same list object as the value for every key, so an append through any key shows up under all of them.
Exercise
You have data = {"user": {"name": "Ana"}, "meta": {"v": 1}} and want a new dictionary where user["name"] is "Ben" and data is untouched, without using deepcopy. Write the expression, and say which branch is shared.
Show answer
new = {**data, "user": {**data["user"], "name": "Ben"}}. The "meta" branch is shared, because new["meta"] is data["meta"]. The "user" branch is a new dictionary.