Theory

Dictionaries store data as key-value pairs.

Create a dictionary:

person = {"name": "Alice", "age": 25}

Access values by key:

print(person["name"]) # Alice

Add or change values:

person["city"] = "Moscow"
person["age"] = 26

Get all keys and values:

print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Alice', 26, 'Moscow'])

Check if key exists:

if "name" in person:
print("Has name!")

Exercises in this lesson

3

Add to Dictionary

Start with: book = {"title": "Python"} Add two new keys: - "author": "John" - "pages": 300 Print the updated dictionary.

Easy Points: 15
4

Loop Through Dictionary

Given: scores = {"Math": 90, "English": 85, "Science": 95} Print each subject and score in format: "Math: 90" "English: 85" "Science: 95"

Medium Points: 20
Solve in the playground
Next lesson: Tuples →