Dictionaries: Labeled Storage

 

What you’ll learn in this lesson

  • What a dictionary is, and how it differs from a list
  • How to make one with keys and values
  • How to read, change, and add entries
  • When to choose a dictionary over a list
  • How to loop through keys and values

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

  • List when order matters and items are alike: a week’s
    temperatures, a shopping list, the letters of a word. You ask “what
    is item number 2?”
  • Dictionary when each item has a name: a student’s details, a
    product’s price, a game’s settings. You ask “what is the value
    labeled price?”

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.


Dictionaries: Labeled Storage

Python for Absolute Beginners · Lesson 13

What you’ll learn

  • What a dictionary is, and how it differs from a list
  • How to make one with keys and values
  • How to read, change, and add entries
  • When to choose a dictionary over a list
  • How to loop through keys and values
1 / 13

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
  • A list answers “what is item number 2?” — a dictionary answers “what is the value labeled name?”
2 / 13

Make a dictionary

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

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

Python shows string keys in single quotes — that is just how it displays them, and it means the same thing.

3 / 13

Reading an entry

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

Mia
9

Square brackets, just like a list — but with the key instead of a position. A missing key gives a KeyError.

4 / 13

Changing and adding entries

  • Changing an entry and adding one look exactly alike
  • The only difference is whether the key already exists
  • Assigning to an existing key replaces it
  • Assigning to a new key adds a brand-new entry
  • Same syntax, two jobs — Python decides by whether the key is already there
5 / 13

Change and add

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

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

The age entry was replaced, because “age” already existed; the pet entry was added, because it did not.

6 / 13

List or dictionary?

  • List when order matters and items are alike: a week's temperatures, a shopping list
  • Dictionary when each item has a name: a student's details, a product's price
  • Storing labeled data in a list means memorizing that position 0 is the name and position 1 is the age
  • A dictionary removes that memorizing: the label travels with the value
7 / 13

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
  • for key, value in … unpacks each pair into two loop variables at once
  • str(value) converts a number to text, because + cannot join text and a number directly
8 / 13

Loop with .items()

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

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

The first loop prints keys only; the second prints each key and value on its own line.

9 / 13

Hands-on exercise

  • Make a dictionary for yourself with keys “name”, “age”, and “city”, and print the whole dictionary
  • Print just the value labeled “city”
  • Change your age entry to next year's age and print the dictionary again
  • Add a new entry for your favorite color and print the dictionary again
  • Loop through your dictionary with .items() and print each key and value on its own line
10 / 13

Key takeaways

  • A dictionary stores entries as key: value pairs inside curly brackets.
  • Read with dict[key]; a missing key gives a KeyError.
  • Assigning to an existing key replaces it; assigning to a new key adds it.
  • Choose a list when order matters, a dictionary when items have labels.
  • .items() loops through key-value pairs together; str() converts a number to text for joining.
11 / 13

Take the quiz

Take the Lesson 13 quiz — 5 quick questions to check what you learned.

12 / 13

Next lesson

Debugging: Reading Error Messages and Fixing Bugs

13 / 13

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.

Download the Lesson 13 slides (PowerPoint, with narration)

Download the Lesson 13 slides (PDF)

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.

Lesson 13: Dictionaries: Labeled Storage

A dictionary stores values under labels (keys) instead of positions. Change the age entry and run again.

Loading Python… this can take a few seconds the first time. Please wait — the Run button will become available when Python is ready.

Try this: Change the age to 11 and press Run again — only the age entry in the dictionary changes.

The code that runs



Output

Press Run to see the output here.

Practice file

Save this as lesson13-practice.py and run it with F5 in IDLE.

# 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))

Key takeaways

  • A dictionary stores entries as key: value pairs inside curly brackets.
  • Read with dict[key]; a missing key gives a KeyError.
  • Assigning to an existing key replaces it; assigning to a new key adds it.
  • Choose a list when order matters, a dictionary when items have labels.
  • .items() loops through key-value pairs together; str() converts a number to text for joining.

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


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.