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
profile = {"name": "Maya", "level": 1}
profile["level"] = 2
print(profile["name"])
print(profile["level"])Maya
2A dictionary connects each key to a value. Assigning to an existing key updates that value.
02. Use a fallback
settings = {"theme": "dark"}
print(settings.get("sound", "on"))
settings["sound"] = "off"
print(settings.get("sound", "on"))on
offget() 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 runNeed input()? Add one value per line
Your output appears here.
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.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Looking up a missing key
learner = {"name": "Maya"}
print(learner["score"])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
learner = {"name": "Maya"}
print(learner[0])learner = {"name": "Maya"}
print(learner["name"])What happens: KeyError because 0 is not a key.
Dictionary lookup uses keys, not numeric positions.