Python

Lesson 7 of 10

Lesson ยท 12 min

Dictionaries

Values with names

A list keeps values in order, and you find them by position. A dictionary keeps values with keys, and you find a value by its key. Each key with its value is a pair.

pet = {
    "name": "Biscuit",
    "age": 4,
    "is_friendly": True,
}

Reading and changing

Use square brackets with the key.

print(pet["name"])      # Biscuit
pet["age"] = 5          # change a value
pet["color"] = "brown"  # add a new pair

If you ask for a key that does not exist, Python stops with a KeyError. The get method is safer. It gives None, or a default value that you choose.

print(pet.get("weight"))            # None
print(pet.get("weight", "unknown")) # unknown

Useful tools

  • "name" in pet is True when the key exists.
  • pet.keys() gives the keys, pet.values() gives the values, and pet.items() gives the pairs.
  • len(pet) is the number of pairs.
for key, value in pet.items():
    print(key, value)

Dictionaries inside lists

Most real data is a list of dictionaries. For example, a list of books, users, or products.

pets = [
    {"name": "Biscuit", "age": 4},
    {"name": "Pepper", "age": 2},
]

for pet in pets:
    print(pet["name"], "is", pet["age"])

Your turn

The dictionary book is already in the editor. Write your code under it. The tasks build on each other, so do them in order.

Tasks

6 to do

  1. Task 1, not checked yet. Add a key named author to book. Its value is the text Tobias Lind.

  2. Task 2, not checked yet. Change the value of pages to 224.

  3. Task 3, not checked yet. Make a variable summary with the text Small Engines by Tobias Lind (224 pages). Build it with an f-string that reads the values from book.

  4. Task 4, not checked yet. Make a variable year with the value of the key year from book. The key does not exist, so use the get method with the default value 'unknown'.

  5. Task 5, not checked yet. Make a variable library. It is a list with two items: book, and a second dictionary with title set to Night Trains and pages set to 188.

  6. Task 6, not checked yet. Use a loop to print the title of each item in library, one on each line.

Task 1 of 6

Add a key named author to book. Its value is the text Tobias Lind.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.