Lesson 8 of 14 · 9 min

Dictionaries

A dictionary stores key: value pairs, so you can look values up by name instead of by position:

capitals = {
    "Zimbabwe": "Harare",
    "Mauritius": "Port Louis",
    "Kenya": "Nairobi",
}

print(capitals["Kenya"])             # Nairobi
capitals["Ghana"] = "Accra"          # add or change an entry
print(len(capitals))                 # 4
print("Mauritius" in capitals)       # True: is that key there?

Asking for a key that is not there is an error (KeyError). .get is safer: it returns a default instead.

capitals.get("France", "unknown")    # "unknown"

Looping

for country, city in capitals.items():
    print(f"{city} is the capital of {country}")

.keys() gives just the keys and .values() just the values.

Counting with a dictionary

A very common pattern: go through items and keep a count per item.

counts = {}
for letter in "banana":
    counts[letter] = counts.get(letter, 0) + 1
print(counts)   # {'b': 1, 'a': 3, 'n': 2}

Your task

The starter has a prices dictionary.

  1. price_of(item): the item's price, or 0 if the shop does not sell it.
  2. basket_total(items): the total price of a list of items, rounded to 2 decimal places (round(x, 2)).
  3. count_words(text): a dictionary of how many times each word appears. Words are separated by spaces (text.split()).
main.py
prices = {"bread": 1.5, "milk": 1.2, "eggs": 2.75, "rice": 3.0}


def price_of(item):
    pass


def basket_total(items):
    pass


def count_words(text):
    pass


print(basket_total(["bread", "eggs", "milk"]))
print(count_words("to be or not to be"))

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…