Sub topic 4
Changing Nested Values in Place
This chapter assumes you can write for loops and simple functions, index lists, and look up dictionary keys. It also assumes you have read the previous chapter on chained indexing, such as data["users"][0]["name"].
By the end you will be able to update, add, and remove values at any depth of a nested structure. You will also know why those changes show up through every name that refers to the structure.
The working model: chained access returns the real object
Lists and dictionaries are mutable, which means they can be changed after they are created. When you write order["customer"], Python does not copy the inner dictionary. It hands you a reference to the same object stored inside order.
A chained expression is therefore a series of lookups. Every step but the last returns a real inner container. The last step is the operation itself, such as an assignment or a method call.
In settings["ui"]["theme"] = "light", the part settings["ui"] is a lookup. The part ["theme"] = "light" is a store into the inner dictionary. Nothing is rebuilt or copied.
Updating existing values
Use one index or key per level, and put the assignment on the last one.
order = {
"id": 1001,
"customer": {"name": "Ana", "address": {"city": "Lisbon"}},
"items": [
{"sku": "A1", "qty": 2},
{"sku": "B7", "qty": 1},
],
}
order["customer"]["address"]["city"] = "Porto"
order["items"][0]["qty"] += 1
order["items"][1]["qty"] = 5
print(order["customer"]["address"]["city"]) # Porto
print(order["items"]) # [{'sku': 'A1', 'qty': 3}, {'sku': 'B7', 'qty': 5}]Augmented assignment such as += works at any depth. Python looks up the container once, reads the current value, and stores the result back.
Keeping a reference to an inner container
If you change several fields of the same inner object, save the inner object in a variable first. This is shorter and avoids repeating the same chain.
address = order["customer"]["address"]
address["city"] = "Faro"
address["zip"] = "8000"
print(order["customer"]["address"]) # {'city': 'Faro', 'zip': '8000'}The variable address is an alias, a second name for the same dictionary. Changing it through address changes it inside order, because there is only one dictionary.
Rebinding is not mutating
Assigning to a bare variable never changes the structure it came from. It only points the variable at something else.
address = {"city": "Braga"} # rebinds the name only
print(order["customer"]["address"]["city"]) # FaroThis is the most common surprise in this chapter. To change the structure, the assignment target must be a subscript such as x["key"] or x[0], or you must call a mutating method on the object. The same trap appears in loops.
prices = {"apple": [1.0, 2.0, 3.0]}
for price in prices["apple"]:
price = price * 2 # rebinds the loop variable only
print(prices) # {'apple': [1.0, 2.0, 3.0]}
for index, price in enumerate(prices["apple"]):
prices["apple"][index] = price * 2
print(prices) # {'apple': [2.0, 4.0, 6.0]}The first loop changes nothing, because price is a name bound to each number in turn. The second loop uses the index to assign into the list. Numbers, strings, and tuples are immutable, so you must store a new value into the container that holds them.
Adding new values
What you do depends on whether the parent container exists and which kind it is.
| Goal | Dictionary | List |
|---|---|---|
| Set or replace one value | `d[key] = value` | `lst[i] = value` (index must exist) |
| Add to the end | not applicable | `lst.append(x)` |
| Add several values | `d.update(other)` | `lst.extend(more)` |
| Add at a position | not applicable | `lst.insert(i, x)` |
| Add only if missing | `d.setdefault(key, default)` | check `len(lst)` first |
New keys and appended items
order["customer"]["email"] = "[email protected]"
order["items"].append({"sku": "C3", "qty": 4})
order["items"].extend([{"sku": "D9", "qty": 1}])
order["items"].insert(0, {"sku": "Z0", "qty": 10})
print(len(order["items"])) # 5
print(order["items"][0]["sku"]) # Z0Assigning to a dictionary key creates it if it is missing. A list does not work that way. lst[5] = x raises IndexError if the list has fewer than six items. Use append or insert to grow a list.
The parent must already exist
Assignment only creates the last level. If an earlier level is missing, Python raises KeyError while looking it up.
profile = {"name": "Ben"}
# profile["scores"].append(88) # KeyError: 'scores'
profile.setdefault("scores", []).append(88)
profile.setdefault("scores", []).append(91)
print(profile) # {'name': 'Ben', 'scores': [88, 91]}setdefault(key, default) returns the existing value if the key is present. Otherwise it stores default and returns it. That makes it a compact way to create a container the first time and reuse it afterward. A new empty list is built on every call, even when the key already exists, but that cost is small for ordinary programs.
update() is shallow
dict.update() replaces whole values for the keys you pass. It does not merge nested dictionaries.
settings = {"ui": {"theme": "dark", "font": 12}}
settings.update({"ui": {"theme": "light"}})
print(settings) # {'ui': {'theme': 'light'}}
settings = {"ui": {"theme": "dark", "font": 12}}
settings["ui"].update({"theme": "light"})
print(settings) # {'ui': {'theme': 'light', 'font': 12}}The first call discards font because the entire "ui" value was replaced. The second call updates the inner dictionary itself, so font survives. The |= operator behaves like update() and has the same limit.
Removing values
Removal also acts on the innermost container, so you reach it first and then remove from it.
| Goal | Syntax | Notes |
|---|---|---|
| Delete a dictionary key | `del d[key]` | `KeyError` if missing |
| Remove and get a dictionary value | `d.pop(key)` or `d.pop(key, default)` | The default avoids `KeyError` |
| Delete a list item by position | `del lst[i]` or `lst.pop(i)` | `pop()` with no argument removes the last item |
| Remove a list item by value | `lst.remove(x)` | Removes only the first match; `ValueError` if absent |
| Empty a container | `container.clear()` | The container object stays |
order = {
"customer": {"name": "Ana", "email": "[email protected]"},
"items": [{"sku": "A1"}, {"sku": "B7"}, {"sku": "C3"}],
}
del order["customer"]["email"]
removed = order["items"].pop(1)
print(removed) # {'sku': 'B7'}
print(order)
# {'customer': {'name': 'Ana'}, 'items': [{'sku': 'A1'}, {'sku': 'C3'}]}Do not remove from a list while looping over it
Removing items shifts the later ones left. The loop's hidden position counter then skips an element.
rows = [{"id": 1, "qty": 0}, {"id": 2, "qty": 0}, {"id": 3, "qty": 4}]
for row in rows:
if row["qty"] == 0:
rows.remove(row)
print(rows) # [{'id': 2, 'qty': 0}, {'id': 3, 'qty': 4}]The row with id 2 should have been removed too, but the loop moved past it. Build the filtered list instead, then assign it back with a slice so every reference to the original list sees the change.
cart = {"items": [{"sku": "A1", "qty": 0}, {"sku": "B7", "qty": 2}, {"sku": "C3", "qty": 0}]}
alias = cart["items"]
cart["items"][:] = [item for item in cart["items"] if item["qty"] > 0]
print(cart) # {'items': [{'sku': 'B7', 'qty': 2}]}
print(alias) # [{'sku': 'B7', 'qty': 2}]The slice assignment [:] = replaces the contents of the existing list object. Writing cart["items"] = [...] would store a new list and leave alias pointing at the old one. Which form you want depends on whether other code holds a reference to the old list.
For dictionaries, adding or deleting keys during iteration over that same dictionary raises RuntimeError: dictionary changed size during iteration. Loop over list(d) or list(d.items()), which is a snapshot, and then change d.
inventory = {"fruit": {"apple": 3, "pear": 0}, "veg": {"kale": 0}}
for category in inventory.values():
for name in list(category):
if category[name] == 0:
del category[name]
print(inventory) # {'fruit': {'apple': 3}, 'veg': {}}Changing the value for an existing key during iteration is safe, because the dictionary's size does not change.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError` on an assignment-looking line | An intermediate level is missing | Create it first with `setdefault()` or an explicit assignment |
| `IndexError: list assignment index out of range` | Assigning to a position that does not exist | Use `append()` or `insert()` |
| `TypeError: 'int' object does not support item assignment` | The chain ended on a number or string, not a container | Check how many levels you actually need |
| `TypeError: 'tuple' object does not support item assignment` | The container is an immutable tuple | Rebuild the tuple, or store a list instead |
| A loop changes nothing | The loop variable was rebound | Assign through the container, using `enumerate()` for lists |
| Data vanishes after `update()` | A nested dictionary was replaced whole | Call `update()` on the inner dictionary |
| Changes appear in an unexpected place | Two names share one object | See the next chapters on shared references and copying |
The last row matters most. In-place changes are visible through every reference, and that is useful when it is intended. It is a source of bugs when two parts of a program share one structure by accident. Later chapters cover how to detect that and how to make independent copies.
Choosing an approach
- Use direct chained assignment when the path is short and every level is known to exist.
- Save an inner container in a variable when you change several fields of it.
- Use
setdefault()when a level may be missing and you are about to add to it. - Rebuild with a comprehension and slice assignment when you are removing many items from a list.
- If you keep writing long chains of lookups with many special cases, the structure may be too deep. The final chapter returns to that point.
Exercise
Given data = {"teams": {"red": {"scores": [3, 5]}}}, write statements that (1) add a score of 7 to the red team, (2) add a team "blue" with an empty scores list if it does not exist and append 4 to its scores, and (3) remove the first score of the red team. What does data contain at the end?
Show answer
One solution: data["teams"]["red"]["scores"].append(7) data["teams"].setdefault("blue", {"scores": []})["scores"].append(4) del data["teams"]["red"]["scores"][0] Final value: {'teams': {'red': {'scores': [5, 7]}, 'blue': {'scores': [4]}}}
Exercise
A learner writes this code to double every quantity in cart = {"items": [{"qty": 1}, {"qty": 2}]} and finds that nothing changes. Explain why, then fix it.
for item in cart["items"]:
qty = item["qty"]
qty = qty * 2
Show answer
The line qty = qty * 2 rebinds the local name qty to a new number. It never stores anything back into the dictionary. Assign through the dictionary instead:
for item in cart["items"]:
item["qty"] = item["qty"] * 2
Here item is a reference to the real inner dictionary, so the subscript assignment changes the data in cart. Afterward cart is {'items': [{'qty': 2}, {'qty': 4}]}.
Exercise
Why does config.update({"db": {"port": 5433}}) lose the existing host key under config["db"], and what single line changes only the port?
Show answer
update() is shallow. It replaces the whole value stored under "db" with the new dictionary that has only "port". To change only the port, write config["db"]["port"] = 5433 or config["db"].update({"port": 5433}).