Lesson 13: Dictionaries: Labeled Storage


What you'll learn in this lesson


Labels instead of positions

A list finds things by position: item 0, item 1, item 2. A dictionary finds things by label. Each entry has two parts: a key (the label) and a value (what is stored under it). Entries sit inside curly brackets, written key: value and separated by commas:

student = {"name": "Mia", "age": 9, "grade": "4th"}
print(student)

Output:

{'name': 'Mia', 'age': 9, 'grade': '4th'}

Python prints the whole dictionary back, curly brackets and all. Note that Python shows string keys in single quotes even though you typed double quotes — that is just how Python displays them, and it means the same thing.

The difference from a list is the question you ask. A list answers "what is item number 2?" A dictionary answers "what is the value labeled name?" When your data has natural labels — a person's name and age, a product and its price — a dictionary is the honest shape for it.


Reading, changing, and adding entries

You read an entry with square brackets, just like a list — but with the key instead of a position:

student = {"name": "Mia", "age": 9, "grade": "4th"}
print(student["name"])
print(student["age"])

Output:

Mia
9

Asking for a key that does not exist gives an error (a KeyError), which is the dictionary version of asking a list for a position past its end. If you are unsure whether a key exists, that error is your signal to check your spelling or your data.

Changing an entry and adding one look exactly alike — the only difference is whether the key already exists:

student = {"name": "Mia", "age": 9, "grade": "4th"}
student["age"] = 10
print(student)
student["pet"] = "Biscuit"
print(student)

Output:

{'name': 'Mia', 'age': 10, 'grade': '4th'}
{'name': 'Mia', 'age': 10, 'grade': '4th', 'pet': 'Biscuit'}

student["age"] = 10 replaced the old age, because "age" was already a key. student["pet"] = "Biscuit" added a brand-new entry, because "pet" was not. Same syntax, two jobs — Python decides by whether the key is already there.


List or dictionary? Ask what the question is

A common beginner mistake is storing labeled data in a list and then having to remember that position 0 is the name, position 1 is the age, and position 2 is the grade. A dictionary removes that memorizing: the label travels with the value.


Looping through a dictionary

A for loop over a dictionary walks its keys. If you also want the values, .items() gives you both at once:

student = {"name": "Mia", "age": 10, "grade": "4th"}
for key in student:
    print(key)
for key, value in student.items():
    print(key + ": " + str(value))

Output:

name
age
grade
name: Mia
age: 10
grade: 4th

Two details here. First, for key, value in ... unpacks each pair into two loop variables at once — the same multiple-assignment idea as putting two values into two variables in one line. Second, str(value) converts the number 10 into the text "10", because + cannot join text and a number directly (Lesson 5's rule: text joins, numbers add — and here you need text). Converting a value with str() is a small tool you will reach for often.


Hands-on exercise

  1. Make a dictionary for yourself with keys "name", "age", and "city", and print the whole dictionary.
  2. Print just the value labeled "city".
  3. Change your age entry to next year's age and print the dictionary again.
  4. Add a new entry for your favorite color and print the dictionary.
  5. Loop through your dictionary with .items() and print each key and value on its own line.

Quick quiz

  1. What is a dictionary, and what are its two parts?
  2. How is a dictionary different from a list?
  3. What happens if you ask for a key that does not exist?
  4. What is the difference between student["age"] = 10 and student["pet"] = "Biscuit"?
  5. Why is str(value) needed in the loop that prints key + ": " + str(value)?

Answer key: 1. Labeled storage: each entry has a key (the label) and a value. 2. A list finds items by position; a dictionary finds them by label. 3. A KeyError. 4. The first replaces an existing entry; the second adds a new one — Python decides by whether the key already exists. 5. Because + cannot join text and a number directly, so the number must first be converted to text.


Key takeaways

Next lesson: Debugging: Reading Error Messages and Fixing Bugs.


Slides

Work through the slides with Helio's narration, or download them:

Open the slidesDownload PowerPointDownload PDF

Try it yourself

Run the lesson's example with real Python, right in your browser (Python loads from the internet, so you need to be online).

Open the demo

Practice file

Download lesson13-practice.pyDownload the solution

# Lesson 13: Dictionaries — Labeled Storage
# WHAT TO DO: A dictionary stores entries as label: value pairs inside
# curly brackets, and you read a value by its label. This dictionary
# describes a student, but it is missing a favorite-color entry.
# Fill in line 13: replace TODO with a real color, keeping it in quotes.
# HINT: Assigning to a new label adds a new entry. The loop below
# already prints every label and value on its own line.
# Run with F5 in IDLE. You are done when the dictionary shows a real color.

student = {"name": "Coder", "age": 12, "city": "Springfield"}
print(student)
print(student["city"])
student["color"] = "TODO"  # <-- CHANGE THIS LINE: your favorite color
print(student)
for key, value in student.items():
    print(key + ": " + str(value))

Save the file as lesson13-practice.py and run it with F5 in IDLE. On a Mac, if F5 does nothing, use Run, then Run Module, from the menu.

Check yourself

Five quick questions on this lesson. Take the Lesson 13 quiz

Want graded quizzes and progress tracking?

Enroll free in the full course — same 17 lessons, with your progress saved. Free, no payment.