IntermediateLesson firstCategory 3 of 20

Dictionaries — Basics

Create and modify key-value pairs. Read the lesson first, then move through the exercises in order.

12 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Inventory Merge

Study 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().

python
user = {"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.

python
print(user["name"]) # Lina

Safe access with get()

get() returns a default value if the key is missing.

python
print(user.get("city", "Unknown"))

Adding and updating keys

Assign a value to a key to add or update it.

python
user["country"] = "Canada" # add user["age"] = 29 # update

Removing keys

Use del, pop(), or popitem().

python
del user["country"] age = user.pop("age") # removes and returns

Checking if a key exists

Use the in keyword before accessing.

python
print("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.

python
original = {"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+).

python
base = {"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.