Sub topic 4
Changing nested values in place
This chapter assumes you can index lists and look up dictionary keys. It also assumes you know basic for loops and how to read a nested value with chained indexing, such as students[1]["grades"][2]. Here you will use the same chains to change data.
Assignment targets the last step of the chain
Python evaluates a chain from left to right. Every step except the last only fetches an object. The last step is the one that changes something.
Nothing is copied along the way. Each step returns the actual inner object, so a change made at the end shows up in the original structure.
Updating and adding values
Assigning to an existing index or key replaces the value. Assigning to a new dictionary key adds it.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
students[0]["grades"].append(95) # grow an inner list
students[1]["grades"][0] = 75 # replace one list item
students[1]["email"] = "[email protected]" # add a new key
print(students[0]) # {'name': 'Ana', 'grades': [90, 85, 95]}
print(students[1]) # {'name': 'Ben', 'grades': [75, 88, 92], 'email': '[email protected]'}Augmented assignment works at any depth. update() merges several keys into an inner dictionary at once.
scores = {"ana": {"math": 90}}
scores["ana"]["math"] += 5
scores["ana"].update({"art": 80, "music": 70})
print(scores) # {'ana': {'math': 95, 'art': 80, 'music': 70}}Lists have a similar limit. You cannot assign to an index past the end, so grades[5] = 1 on a three-item list raises IndexError. Use append() or insert() to add items.
Removing values
Which tool you use depends on what you know and what you need back.
| Goal | Tool | Notes |
|---|---|---|
| Remove a dictionary key | `del d["key"]` | `KeyError` if the key is missing |
| Remove a key and keep its value | `d.pop("key")` | `d.pop("key", None)` avoids the error |
| Remove a list item by position | `del lst[i]` or `lst.pop(i)` | `pop()` with no argument takes the last item |
| Remove a list item by value | `lst.remove(x)` | Removes only the first match |
students = [
{"name": "Ana", "grades": [90, 85, 95]},
{"name": "Ben", "grades": [75, 88, 92], "email": "[email protected]"},
]
last = students[1]["grades"].pop() # 92
del students[1]["email"]
students[0]["grades"].remove(85)
print(last) # 92
print(students)
# [{'name': 'Ana', 'grades': [90, 95]}, {'name': 'Ben', 'grades': [75, 88]}]Pitfalls
Removing items from a list while you loop over it skips elements, because the later items shift left under the loop's index. To filter, build a new list or assign a slice:
grades = [50, 90, 40, 85]
grades[:] = [g for g in grades if g >= 60]
print(grades) # [90, 85]The slice assignment grades[:] = ... changes the existing list. Writing grades = [...] would only point the name grades at a new list. Any other name or structure that holds the old list would not see the change. If grades came from students[0]["grades"], the dictionary would still hold the old list. This is the first hint of the aliasing behavior covered in the shared reference chapter.
Tuples cannot be changed in place. If a tuple holds a list, you can change the list but not replace the tuple's items:
record = ("Ana", [90, 85])
record[1].append(95) # allowed: the inner list is mutable
print(record) # ('Ana', [90, 85, 95])
# record[1] = [] # TypeError: tuple does not support item assignmentExercise
Given data = {"teams": [{"name": "red", "scores": [3, 5]}, {"name": "blue", "scores": [4]}]}, write statements that (1) add the score 7 to the blue team, (2) change the first red score to 10, and (3) delete the "name" key from the red team. What does data["teams"][0] look like afterward?
Show answer
data["teams"][1]["scores"].append(7); data["teams"][0]["scores"][0] = 10; del data["teams"][0]["name"]. Afterward data["teams"][0] is {'scores': [10, 5]}.