← All lessons

Nested structures

Sign in · Sign up

Lesson 5.12

Collections can be nested inside each other. A list of dictionaries is like a table where each row is a dictionary:

heroes = [
    {"name": "Mia", "hp": 100},
    {"name": "Timur", "hp": 80},
]

print(heroes[0]["name"])   # Mia

It reads left to right: first the index in the list, then the key in the dictionary — heroes[0]["name"], not heroes["name"].

The list of heroes is set by the check. Print, in order:

  1. the name of the first hero with an index and a key;
  2. the name and health hp of every hero, one line per hero.
Hint

A dictionary inside a list is read left to right: first the position in the list, then the key.

The first hero is [0], its name is the key "name". For all heroes use a for over the list, and inside take hero["name"] and hero["hp"].

A hero line is one line per hero, the name and hp separated by a colon:

print(f'{hero["name"]}: {hero["hp"]} HP')   # Mia: 100 HP

Two separate print calls give two lines and won't match the expected output.