Nested data
Lists of dictionaries and dictionaries of lists. How real apps store data.
Code runs right here in your browser. Nothing to install.
Learn it
Real data nests. Reach in one step at a time, like players[0]["name"].
Real data is often nested. A list of dictionaries is like a table: each dictionary is a row. players = [{"name": "Ava", "score": 90}, {"name": "Ben", "score": 72}].
Reach inside step by step: players[0]["name"] means "the first player, then their name". A dictionary of lists works too: teams = {"red": ["Ava", "Ben"]}, so teams["red"][1] is "Ben".
You can sort a list of dictionaries by a value using a small helper function as the key.
players = [ {"name": "Ava", "score": 90}, {"name": "Ben", "score": 72}, {"name": "Cleo", "score": 85}, ] print(players[0]["name"]) for p in players: print(p["name"], "-", p["score"]) def by_score(p): return p["score"] best = max(players, key=by_score) print("Best:", best["name"])
Try it yourself
+10 XPAdd a new student {"name": "Dev", "grade": 64} to the list, then print the name of every student with a grade of 70 or more.
Create a free account to start this lab
Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.
Capture the flag
+10 XPFor data = {"red": ["Ava", "Ben"]}, what is data["red"][1]?
Create a free account to start this lab
Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.
Class report
+20 XPUsing the scores dictionary of lists, print each student's average rounded to 1 place, like Ava: 84.3. Then print the student with the highest average: Top student: Ava.
Create a free account to start this lab
Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.