← All lessons

Dictionaries

Sign in · Sign up

Lesson 5.9

A dictionary stores key → value pairs. It is written in curly braces, with pairs separated by commas:

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

To read a value, use the key in square brackets:

print(ages["Mia"])   # 14

A key is unique: the same key never appears twice in a dictionary. An index like in a list doesn't work here — ages[0] won't find the first item.

The dictionary ages and the key key are set by the check. Print, in order:

  1. the value for the key key;
  2. whether key is in the dictionary — with in;
  3. the dictionary itself.
Hint

Access by key uses square brackets: d["name"].

The key goes in the brackets, not a number: a dictionary has no indexes. If the key is missing, the dictionary raises a KeyError — that is worth seeing too.