← Back to course
Code Crew G6+ / Week 09 / Thursday
4/6
Week 09 Β· Structured data

Thursday

Read, change, write back
// Saving lists and dictionaries with JSON
⏱ about 30 min

Thursday: Read, change, write back

Another mission is complete, and every crew member's mission count needs to go up by one. Nova has also earned her place on the crew list at last.

Rocket rubs his hands together. "Load the file, add one to everybody, add Nova, save. Four steps."

Raven raises a finger. "What do you notice if we run it twice by accident?" she asks. "The counts go up twice, which is fair, because two runs means two missions. But Nova would be added twice."

Nova laughs, a soft chime. "Interesting," she says. "Two of me would be confusing. Check whether a name is already on the list before adding it."

Rocket writes a small helper function to look up a crew member by name.

The read, change, write pattern

  1. Load the data from the JSON file with json.load.
  2. Change the Python data: update values, add records, remove records.
  3. Write the whole thing back with json.dump, using mode "w".
# update_crew.py
import json

def find_member(crew, name):
    """Give back the record with this name, or None."""
    for member in crew:
        if member["name"] == name:
            return member
    return None

with open("crew.json") as f:
    crew = json.load(f)

for member in crew:
    member["missions"] = member["missions"] + 1

if find_member(crew, "Nova") is None:
    crew.append({"name": "Nova", "role": "companion", "missions": 1})

with open("crew.json", "w") as f:
    json.dump(crew, f, indent=2)

for member in crew:
    print(member["name"], member["missions"])

Starting from Tuesday's crew.json, the first run shows:

Rocket 4
Raven 5
Nova 1

The second run loads the updated file. Nova is found, so she is not added again:

Rocket 5
Raven 6
Nova 2
After a third run, what number is shown for Rocket?
After a third run, how many crew records are in the file?
THE HELPER FUNCTION
  • Read the question.
  • Tap your answer.
find_member(crew, "Comet") is called, and nobody is named Comet. What does it give back?
At your computer
1. Run save_crew.py once to reset crew.json to two members.
2. Type update_crew.py, save it and run it. Check the three lines.
3. Run it again. Check that Nova appears only once.
4. Open crew.json in IDLE and look at the updated file.
5. Challenge: add a fourth member with a role you invent, using find_member to avoid doubles.

Practice: remove finished tasks

Removing records uses the same pattern. Load the list, build a new list with only the records to keep, then write the new list back.

# clear_done.py
import json

with open("tasks.json") as f:
    tasks = json.load(f)

remaining = []
for task in tasks:
    if not task["done"]:
        remaining.append(task)

with open("tasks.json", "w") as f:
    json.dump(remaining, f, indent=2)
print(f"Cleared {len(tasks) - len(remaining)}, kept {len(remaining)}")
[
  {"name": "Check fuel", "done": true},
  {"name": "Check weather", "done": false},
  {"name": "Seal doors", "done": true}
]

Starting from the tasks.json above, the program shows Cleared 2, kept 1.

READ CLEAR_DONE.PY
  • Read the question.
  • Tap your answer.
Which task is kept?
You run clear_done.py a second time. What does it show?
Why build a new list instead of removing items during the loop?
If all three tasks were done, how many are kept?
What does not False give?
Which mode writes the new list back?
StatementTrue or false?
Read, change, write back saves the whole list each time.?
Mode "a" is right for writing back a changed JSON list.?
A record is often stored as a dictionary.?
The program changes tasks.json without loading it first.?
WHY THIS EXERCISEThe pattern loads the data, changes it in Python, and replaces the file with "w".

Read, change, write back is how real apps update saved data. Tomorrow you will handle the very first run, when there is no file yet.

← Wednesday