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.
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.
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.
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.
"name", "age", and
"city", and print the whole dictionary."city"..items() and print each key
and value on its own line.student["age"] = 10 and student["pet"] = "Biscuit"?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: value pairs inside curly brackets.dict[key]; a missing key gives a KeyError..items() loops through key-value pairs together; str() converts a number to text for joining.Next lesson: Debugging: Reading Error Messages and Fixing Bugs.
Work through the slides with Helio's narration, or download them:
Open the slidesDownload PowerPointDownload PDF
Run the lesson's example with real Python, right in your browser (Python loads from the internet, so you need to be online).
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.
Five quick questions on this lesson. Take the Lesson 13 quiz
Enroll free in the full course — same 17 lessons, with your progress saved. Free, no payment.