Python Basics · Lesson 11 of 12

Dictionaries

A list finds things by position. A dictionary finds things by name. It stores pairs: a key and the value that belongs to it.

prices = {
    "apple": 0.5,
    "bread": 2.2,
    "milk": 1.1,
}

Dictionaries use curly braces. Each entry is key: value, and entries are separated by commas.

Reading, adding and changing

Use square brackets with the key:

print(prices["bread"])   # 2.2
prices["milk"] = 1.25    # change a value
prices["eggs"] = 3.0     # add a new entry

Adding and changing look the same: if the key exists it is updated, if not it is created.

Asking for a key that is not there stops the program with a KeyError. Two ways to stay safe:

if "tea" in prices:
    print(prices["tea"])

print(prices.get("tea", 0))   # 0 when there is no "tea"

Looping over a dictionary

.items() gives you each key together with its value:

for item, price in prices.items():
    print(item, price)

.keys() gives just the keys, .values() just the values, and len(prices) the number of entries.

Describing one thing

A dictionary is also a natural way to describe a single thing with several properties:

book = {"title": "Dune", "author": "Frank Herbert", "pages": 612}
print(book["title"])

Lists of such dictionaries are how programs usually hold their data: a list of books, of users, of orders.

Your Task

  1. Add a new entry to stock: "pears" with the value 12.
  2. The shop sells 5 apples. Reduce the value of "apples" by 5.
  3. Loop over the dictionary and print each fruit with its count, in the form apples: 15.
  4. After the loop, print the total number of fruits (the sum of all the values).
  • "pears" is in the dictionary with the value 12
  • "apples" is reduced to 15
  • Each fruit is printed in the form apples: 15
  • The total, 35, is printed last