LESSON 11 · BEGINNER PATH10 min

Dictionaries

Store related values by key and retrieve or update them.

Video coming to YouTube

Work through the full lesson and run its code while the video is being prepared for publication.

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.

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.