Dictionaries — Basics
Create and modify key-value pairs. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with Inventory MergeStudy Material
Read the full lesson
What a dictionary is
A dictionary stores data as key-value pairs. You look up a key to get its value, like a real dictionary.
Creating dictionaries
You can create dictionaries with braces or with dict().
pythonuser = {"name": "Lina", "age": 28} settings = dict(theme="dark", lang="en")
Reading values by key
Use brackets to get a value. The key must exist or you will get a KeyError.
pythonprint(user["name"]) # Lina
Safe access with get()
get() returns a default value if the key is missing.
pythonprint(user.get("city", "Unknown"))
Adding and updating keys
Assign a value to a key to add or update it.
pythonuser["country"] = "Canada" # add user["age"] = 29 # update
Removing keys
Use del, pop(), or popitem().
pythondel user["country"] age = user.pop("age") # removes and returns
Checking if a key exists
Use the in keyword before accessing.
pythonprint("name" in user) print("email" in user)
What can be a key
Dictionary keys must be hashable. Strings, numbers, and tuples work. Lists and dictionaries do not.
Copying vs referencing
A copy is independent. A reference points to the same dictionary.
pythonoriginal = {"a": 1} copy = original.copy() copy["a"] = 2
Merging dictionaries
update() changes the dictionary in place. The | operator creates a new one (Python 3.9+).
pythonbase = {"a": 1} extra = {"b": 2} base.update(extra) merged = base | extra
Common mistakes to avoid
- Using a list or dict as a key.
- Accessing missing keys without
get(). - Forgetting that
update()changes the dictionary in place.
What you should understand after this lesson
- How to create, read, add, update, and remove keys.
- How to access keys safely with
get(). - What kinds of keys are allowed.
- How to copy and merge dictionaries.
Interactive
Exercises for this topic
These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.
Inventory Merge
Merge and consolidate multiple dictionaries.
Configuration Fallback
Use the safe lookup features in dictionaries.
State Cleanup
Safely remove elements from dictionaries using popping methods.
Complex Keys
Understand what bounds determine dictionary keys.
Nested Dictionary Access
Navigate complex dictionary trees seamlessly.