Skip to content
BetaDE
Lesson 8 of 35Python

Python · Lesson 8 · 25 minutes

Dictionaries

What you'll learn

  • Store data as pairs of key and value
  • Look up, change and add values
  • Go through all pairs with items()

Look things up instead of counting through

In a list you find values by their position. Often it’s more practical to find a value by a name – like in a dictionary where you look up a word. That’s exactly what a dictionary (type dict) does:

phone_book = {"Mia": "0171 1234", "Ben": "0160 9876"}
print(phone_book["Mia"])

A dictionary consists of pairs: key: value. The key goes before the colon, the value after it. Everything together goes into curly brackets { }.

Changing and adding

With the same notation you change values – or create new pairs if the key doesn’t exist yet. Use Steps to watch the dictionary grow:

player = {"name": "Lena", "level": 3}
player["level"] = 4
player["lives"] = 3
print(player)
print(len(player))

Looking up safely

If you ask for a key that doesn’t exist, the program crashes with a KeyError. Check first with in, or use get() with a fallback value:

grades = {"Maths": 2, "English": 1}

if "Art" in grades:
    print(grades["Art"])
else:
    print("No grade for Art.")

print(grades.get("Sport", "still open"))

Going through all pairs

With .items() you get the key and the value in a loop each time:

scores = {"Team Red": 12, "Team Blue": 15, "Team Green": 9}

for team, score in scores.items():
    print(f"{team} has {score} points")

best = max(scores, key=scores.get)
print(f"{best} is in the lead!")

Remember: Every key appears only once in a dictionary. If you write a key in a second time, the old value is overwritten.

Quick check

Before you start the task: what does this program print? Type your guess – then Python works it out.

ages = {"Ana": 12, "Ben": 13}
ages["Ana"] = ages["Ana"] + 1
print(ages)

Your task

Your turn

The dictionary stock shows how much fruit a shop has. Add bananas with 7 pieces and increase the apples by 3. Then print every fruit that is still in stock (more than 0) on its own line, e.g. apples: 8. Fruit with 0 pieces should not appear.

stock = {"apples": 5, "pears": 0, "kiwis": 12}

# Change the stock and print it:

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

stock = {"apples": 5, "pears": 0, "kiwis": 12}

stock["bananas"] = 7
stock["apples"] = stock["apples"] + 3

for fruit, count in stock.items():
    if count > 0:
        print(f"{fruit}: {count}")
Practise more in the training roomEndless new tasks on this topic – with XP and streaks.