Python todo notebook (3/6): the data model
Add a task, find it by id, toggle done and delete it, while prochain_id stays consistent. The notebook rules live in this chapter, before the menu.
Getting started
Home Assistant
Buying
Add a task, find it by id, toggle done and delete it, while prochain_id stays consistent. The notebook rules live in this chapter, before the menu.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
You already load and save the top-level dictionary. This chapter holds the rules of the notebook, before you polish the menu.
def ajouter_tache(data, titre):
titre = titre.strip()
if not titre:
return False
tid = data["prochain_id"]
data["taches"].append({"id": tid, "titre": titre, "fait": False})
data["prochain_id"] = tid + 1
return True
def trouver_tache(data, tid):
for t in data["taches"]:
if t["id"] == tid:
return t
return None
Compare with == on the integer id. Do not name your own variable id, or you hide the built-in function id().
def basculer_fait(data, tid):
t = trouver_tache(data, tid)
if t is None:
return False
t["fait"] = not t["fait"]
return True
def supprimer_tache(data, tid):
avant = len(data["taches"])
data["taches"] = [t for t in data["taches"] if t["id"] != tid]
return len(data["taches"]) < avant
The ids of the tasks you keep are not reused. That is the simpler choice. prochain_id keeps climbing.
nombre_taches_actives(data): the tasks whose fait is false.reordonner_ids (advanced, and optional): renumber the tasks from 1 to n. Think about the risk if another file still points at the old ids.Part 4 — Command-line menu (a while loop).
A book search for clean Python practice: Amazon.co.uk.
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).