Browser lab18 min+60 XP

Nested data

Lists of dictionaries and dictionaries of lists. How real apps store data.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

Real data nests. Reach in one step at a time, like players[0]["name"].

Key words
playersa listplayers[0]a dictplayers[1]a dictplayers[2]a dict"name": "Ava""score": 90players[0]["name"]  gives  "Ava"
A list of dictionaries. The green path shows 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.

Real life linkYour phone's contacts are nested data: each person has a name, several numbers and maybe an address with its own parts.
Example code
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"])
TASK 2

Try it yourself

+10 XP

Add 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.

TASK 3

Capture the flag

+10 XP

For 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.

HOMEWORK

Class report

+20 XP

Using 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.