Codiqo

Learn Python · lesson 30 of 60 · about 8 minutes

Dictionaries

Price the shopping list: map each thing to its price with a dictionary, and add the list up.

What you'll learn

  • Create a dictionary
  • Read, add and change values by key
  • Loop with items()

What will the shopping cost?

The shopping list from the last unit says what to buy, but not what it costs. A dictionary pairs each thing with its price, in pence: prices["milk"] is 120. The assistant goes through the shopping list, adds up the price of each thing it knows, and lists the things that have no price yet, like a new item Sam just added.

Look things up by name

A dictionary stores pairs: a key and its value. Instead of a position, you look values up by key, like a word in a real dictionary.

{"name": "Phoebe", "coins": 40} has two keys, name and coins.

Reading and changing

player = {"name": "Phoebe", "coins": 40}
print(player["name"])
player["coins"] += 10
player["level"] = 2
print(player)

Output

Phoebe
{'name': 'Phoebe', 'coins': 50, 'level': 2}

Safe lookups and loops

Reading a key that doesn't exist is a KeyError. get(key, default) returns the default instead.

items() gives you each key and value together in a loop.

get() and items()

prices = {"hat": 60, "scarf": 50}
print(prices.get("crown", 0))
for item, cost in prices.items():
    print(f"{item}: {cost}")

Output

0
hat: 60
scarf: 50

Tip

Prices are kept in pence, as whole numbers, so adding them never gives a long decimal. Dividing by 100 and printing with :.2f turns 580 into 5.80.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.