← All lessons

Dictionary methods: keys, values, items

Sign in · Sign up

Lesson 5.11

A dictionary can be looped over in three ways:

ages = {"Mia": 14, "Timur": 15}

for name in ages.keys():        # keys
    print(name)

for age in ages.values():       # values
    print(age)

for name, age in ages.items():  # pairs
    print(f"{name}: {age}")

items() is the handiest: it gives you both the key and the value at once. Notice for name, age in ages.items(): — two variables separated by a comma unpack the pair.

The dictionary ages is set by the check. Print, in order:

  1. each name — with keys();
  2. phrases like Name: <name>, age <age> — with items() and an f-string.
Hint

A dictionary loops over its keys: for x in d gives the keys, just like d.keys().

To get both the key and the value, loop over d.items() and unpack the pair into two variables with a comma. Build the phrase with an f-string.