🎓 A1Learner
🔍

Python Dictionaries

A dictionary keeps values by label. A list keeps items in order by position.

Make a dictionary

Curly braces hold the pairs. Each pair is a key, a colon, and a value.

person = {"name": "Ada", "age": 36, "city": "London"}
print(person)

Keys are labels

You read a value by naming its key. You do not count positions.

person = {"name": "Ada", "age": 36}
print(person["name"])
print(person["age"])

Values of any type

A value can be text, a number, a list, or True or False.

student = {"name": "Cy", "scores": [80, 90], "passed": True}
print(student["scores"])
print(student["passed"])

A repeated key

A key can appear only once. The later value wins.

box = {"color": "red", "color": "blue"}
print(box)

Make one with dict()

The dict() constructor builds a dictionary from named values. len() counts the pairs.

person = dict(name="Ada", age=36)
print(person)
print(len(person))

Example

person = {"name": "Mia Chen", "age": 28, "city": "Leeds", "job": "Teacher"}
print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])
print("Job:", person["job"])

Key points

  • Dictionary: a collection that stores key and value pairs
  • Key: the label you use to look up a value
  • Use a colon between each key and its value
  • Use commas to separate one pair from the next
  • Pairs keep the order in which you added them
  • You find values by key, not by position.

In this example, person holds four pairs. Each key is a label for one fact about Mia. The first print reads the value stored under name. The next prints read age, city, and job in the same way. Each lookup uses a key, not a position.

Note

A dictionary has no first item at index 0.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What happens when you write the same key twice in one dictionary?