LESSON 11 · BEGINNER PATH15 min

Dictionaries

Store related values by key and retrieve or update them.

Before you start: Lists

Video lesson: Dictionaries

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    A list is useful when you care about a sequence of items. A dictionary is useful when each value has a meaningful label. Imagine a learner profile with a name, level, study streak, and perhaps a badge. If you put these values in a list, you must remember which position means what. In a dictionary, you can ask for the value under the key name or level. Today we will create and update a profile, handle a missing optional key without crashing, and then use dictionaries for a price list, word counts, and a small catalog. Each example adds one reason to choose a dictionary. We will also inspect two mistakes: looking up a key that is absent and assuming a dictionary uses list positions.

  2. 00:44

    As you watch, name the key and the value separately. A key tells Python where to look; the value is the data you get back. The learner dictionary begins with two key-value pairs. The string name maps to Maya, and level maps to the integer one. Square brackets containing the key name retrieve Maya. The next assignment uses the existing level key and replaces its value with two. Assigning streak with a key that did not exist adds a new pair. When we print the dictionary, we see all its current pairs. The last line asks for badge with get and a fallback string. Because badge is absent, get returns No badge yet.

  3. 01:25

    It does not add a badge to the dictionary. This distinction matters: a fallback supplies a result for that lookup, but it does not modify the stored data. The settings example makes the same behavior visible. Asking for sound with a fallback of on returns on before sound exists. After setting sound to off, the same get call returns the stored off instead of the fallback. Now move to prices. Pen maps to two and Notebook maps to five. Change Pen to three, then loop through prices.items. Each pass gives an item key and its price value together, so the output reports Pen: three dollars and Notebook: five dollars.

  4. 02:06

    Modern Python dictionaries preserve insertion order, but your program should use keys for meaning rather than treating the dictionary as an unnamed row of positions. A word counter shows why a dictionary is more than a profile. Start with an empty counts dictionary. For each word, ask for its current count with get, using zero as the fallback, then add one and save the result under that word. The first red becomes one, the next red becomes two, and the third becomes three. Blue and green each remain at one. This pattern counts categories without a separate variable for every possible word. Finally, consider a product catalog.

  5. 02:48

    A code like P one zero one maps to another dictionary containing the product name and stock. The outer dictionary is a lookup by product code; the inner dictionary describes one product. Before reading the inner record, the example checks whether the code exists in the catalog. Then it subtracts one from stock and prints Pen: two left. This combination of keys and nested records is common in real applications. You can always draw the structure as a set of labeled boxes: product code selects a record, then name or stock selects one field inside that record. Pause and predict the output if the code changes to P one zero two.

  6. 03:30

    Then ask what should happen if the code is absent. The if guard sends that case to Unknown product instead of raising an exception. The first mistake is using square brackets for a key that might not exist. If learner has only name, asking for learner at score raises KeyError. Square brackets are appropriate when a missing key means your program is broken and should be noticed. If the field is genuinely optional, get with a fallback gives a controlled result, such as zero for a score you have not recorded. Choose the fallback carefully: zero is meaningful for a count, while Not earned is clearer for an optional certificate label.

  7. 04:10

    The second mistake is writing learner at zero as if it were a list. A dictionary does not mean first item by numeric index. Python searches for the actual key zero, and if there is no such key, it raises KeyError. Use learner at name when you want the name. A further quiet error is mixing keys that look similar, such as level and levels, or changing the letter case. Python treats those as different strings. When a lookup fails, print the available keys or inspect the dictionary instead of guessing. Remember that a program can also run but produce the wrong count if you use the wrong starting fallback. Trace the first occurrence of a word to check the rule.

  8. 04:53

    For the practical task, add favorite_topic with the value loops to the learner dictionary. Print that value by its key. Then request certificate with get and the fallback Not earned. Predict two lines: loops and Not earned. The first is stored data; the second is an optional-field fallback. Run and Check Task, then try assigning certificate to Completed and repeat the get call. You should now see the stored value instead of the fallback. As a stretch exercise, make a tiny frequency counter for the words cat, dog, cat. Do not write a special variable named cat_count. Let the words become keys and use get with zero to update each count.

  9. 05:35

    The quiz checks key lookup, missing-key errors, and what get returns when a key is absent. Explain each answer in terms of the exact key being read or assigned. After this lesson, you will be ready to import modules that provide more tools than you could reasonably write inside one file.

Understand the concept

A dictionary maps keys to values. It is useful when each piece of data has a meaningful name, such as name, level, or completed. Use square brackets with a key to read or set a value.

Looking up a missing key with square brackets raises KeyError. The get() method can return a fallback value instead. Dictionaries can grow as you add new keys.

  • Key-value pairs
  • Read and update by key
  • get() can supply a fallback

See it step by step

Read the code, predict the output, then compare it with the result.

01. Update a value by key

PYTHON
profile = {"name": "Maya", "level": 1}
profile["level"] = 2
print(profile["name"])
print(profile["level"])
EXPECTED OUTPUT
Maya
2

A dictionary connects each key to a value. Assigning to an existing key updates that value.

02. Use a fallback

PYTHON
settings = {"theme": "dark"}
print(settings.get("sound", "on"))
settings["sound"] = "off"
print(settings.get("sound", "on"))
EXPECTED OUTPUT
on
off

get() returns the fallback only when the key is missing. After adding sound, it returns the stored value.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

Read keys and values together

A dictionary is often more useful as a collection of labeled values than as one isolated lookup. The items() method lets a loop receive each key alongside its value. This is useful for receipts, settings summaries, and simple reports. You can update a value by key before looping, and the report then uses the current data without rewriting its print statements.

Python preserves the insertion order of dictionary entries, so the two lines below follow the order in which the keys were added. Still, use an explicit sort if alphabetical order is part of your requirement. Add a 'Pencil' entry with a price of 1 and predict where it appears. Then try sorted(prices.items()) to see how sorting changes the report.

PYTHON
prices = {"Pen": 2, "Notebook": 5}
prices["Pen"] = 3

for item, price in prices.items():
    print(f"{item}: ${price}")
EXPECTED OUTPUT
Pen: $3
Notebook: $5
Follow the reasoning
  1. Assigning prices['Pen'] replaces its old value of 2.
  2. items() supplies a (key, value) pair on each loop pass.
  3. The loop prints the latest price for each named item.
02 / 03

Count occurrences with a dictionary

When you need to count repeated values, use each value as a key and its count as the mapped number. For every word, read the count so far, add one, and store it back. get(word, 0) treats a word you have not seen yet as having count zero. You do not need a separate if branch for the first occurrence.

This pattern appears in survey results, event logs, and text analysis. The loop makes one pass through the words, while the dictionary keeps the totals by name. Predict how the counts change if 'blue' is added at the end. Then print counts['green'] only after first checking whether that key exists; otherwise a missing key raises KeyError.

PYTHON
words = ["red", "blue", "red", "green", "red"]
counts = {}

for word in words:
    counts[word] = counts.get(word, 0) + 1

print(counts["red"])
print(counts["blue"])
print(counts["green"])
EXPECTED OUTPUT
3
1
1
Follow the reasoning
  1. The first red starts from zero; later reds increment its stored count.
  2. Each color has its own key, so counts stay separate.
  3. The final lookups read the three totals.
03 / 03

Model a record inside a larger lookup

A dictionary value can itself be a dictionary. This is useful when a stable code identifies a record with several fields. The outer dictionary answers 'which item?'; the inner one answers 'which detail about that item?' A structure like this avoids parallel lists of codes, names, and stock levels that could accidentally fall out of alignment.

Before using a code supplied by a user, test whether it exists in the outer dictionary. Once you have a record, update a named field rather than relying on a numeric position. Here a sale lowers the stock of one product only. Change code to 'P102' and predict which stock number changes; then try an unknown code and observe the fallback.

PYTHON
catalog = {
    "P101": {"name": "Pen", "stock": 3},
    "P102": {"name": "Notebook", "stock": 2},
}
code = "P101"

if code in catalog:
    item = catalog[code]
    item["stock"] -= 1
    print(f"{item['name']}: {item['stock']} left")
else:
    print("Unknown product")
EXPECTED OUTPUT
Pen: 2 left
Follow the reasoning
  1. Membership checks the outer dictionary before indexing it.
  2. item refers to the nested record for P101.
  3. Changing item['stock'] updates that record in catalog.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnAdd a "favorite_topic" key with the value "loops". Print it, and use get() to request a "certificate" key with the fallback "Not earned".
Need a hint?

Assign learner['favorite_topic'] = 'loops' and print that key. For the missing certificate key, try learner.get('certificate', 'Not earned').

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.What does {"name": "Maya"}["name"] produce?

    02.What happens when dictionary[key] uses a missing key?

    03.What does {}.get("level", 1) return?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Looking up a missing key

    COMMON MISTAKE
    learner = {"name": "Maya"}
    print(learner["score"])
    FIX
    learner = {"name": "Maya"}
    print(learner.get("score", 0))

    What happens: KeyError for score.
    Use get with a fallback if the key may be absent.

    Using a list-style index

    COMMON MISTAKE
    learner = {"name": "Maya"}
    print(learner[0])
    FIX
    learner = {"name": "Maya"}
    print(learner["name"])

    What happens: KeyError because 0 is not a key.
    Dictionary lookup uses keys, not numeric positions.

    Browse this lesson’s problem fixes