Kids Coding
Data Tables
A list of dictionaries is a tiny table. Loop, filter, and print a report.
A table is a list of dicts
Each dict is a row. Each key is a column. Loop the list. Read the keys you need.
Scores
rows = [
{"name": "Sam", "score": 12},
{"name": "Riley", "score": 8},
{"name": "Jun", "score": 15},
]
for row in rows:
print(row["name"], row["score"])A list of dictionaries is the shape of almost every real dataset: one dictionary per row, the same keys on every row.
Filter
High scores
rows = [
{"name": "Sam", "score": 12},
{"name": "Riley", "score": 8},
{"name": "Jun", "score": 15},
]
for row in rows:
if row["score"] >= 10:
print(row["name"], "passed")Real life
A class mark sheet: name in one column, score in the next.
Each row is a dict. The list is the sheet. Loop it like reading down the page.
Class marks
sheet = [
{"name": "Sam", "mark": 18},
{"name": "Riley", "mark": 12},
{"name": "Jun", "mark": 20},
]
for row in sheet:
if row["mark"] >= 15:
print(row["name"], "passed")Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Loop a list of two dicts with city and print each city.
Show solution
rows = [
{"city": "Lisbon"},
{"city": "Oslo"},
]
for row in rows:
print(row["city"])