Dictionaries — Python

A dictionary stores key: value pairs (a name and its value) inside { }, and menu["sweet tea"] reads a value through its key. menu[key] = value adds a new key…

In a list, the price of sweet tea is at prices[1]. You have to remember that number 1 is sweet tea. As soon as a new item is inserted at the front, the numbers shift, and prices[1] quietly becomes the price of something else.

Mr. Darto never has that problem. The price list on his stall's wall says "coffee with milk $15, sweet tea $5, toast $12". When a customer asks "how much is sweet tea?", he looks for the words sweet tea, not for "row number 2". Each name is written only once. When a price goes up, he changes the number next to that name. Python has a container that works like that price list. It is called a dictionary (type dict). It holds pairs of a key and a value. You look up a value by its name, not by its position.

Creating a dictionary

Here is Mr. Darto's price list as a dictionary, and some ways to check it:

menu = {"coffee with milk": 15, "sweet tea": 5, "toast": 12}

print(menu)                  # {'coffee with milk': 15, 'sweet tea': 5, 'toast': 12}
print(menu["sweet tea"])     # 5
print(len(menu))             # 3
print("sweet tea" in menu)   # True
print(15 in menu)            # False

Adding, changing, deleting

The three lines in the middle change what menu holds:

menu = {"coffee with milk": 15, "sweet tea": 5, "toast": 12}
menu["iced orange"] = 8     # a new key: added
menu["sweet tea"] = 6       # an existing key: its value is replaced
del menu["toast"]           # delete the key and its value
print(menu)                 # {'coffee with milk': 15, 'sweet tea': 6, 'iced orange': 8}

This table shows what menu holds after each line:

Line What menu holds afterwards
menu["iced orange"] = 8 {'coffee with milk': 15, 'sweet tea': 5, 'toast': 12, 'iced orange': 8}
menu["sweet tea"] = 6 {'coffee with milk': 15, 'sweet tea': 6, 'toast': 12, 'iced orange': 8}
del menu["toast"] {'coffee with milk': 15, 'sweet tea': 6, 'iced orange': 8}

A key that isn't there

This is what happens when the program reads menu["iced orange"] from the first menu, which does not have that key yet:

Traceback (most recent call last):
  File "/home/darto/stall.py", line 2, in <module>
    print(menu["iced orange"])
          ~~~~^^^^^^^^^^^^^^^
KeyError: 'iced orange'

Reading a missing key with square brackets gives an error right away: KeyError, followed by the key you asked for. The result is not None, and not 0.

When the key might be missing, use .get():

menu = {"coffee with milk": 15, "sweet tea": 5, "toast": 12}
print(menu.get("iced orange"))     # None
print(menu.get("iced orange", 0))  # 0
print(menu.get("sweet tea", 0))    # 5

Going through a dictionary with for

This loop prints each menu item with its price:

menu = {"coffee with milk": 15, "sweet tea": 5, "toast": 12}
for name, price in menu.items():
    print(f"{name}: {price}")

The output:

coffee with milk: 15
sweet tea: 5
toast: 12

Counting with a dictionary

Mr. Darto wants to know how many times each menu item was ordered today. A dictionary is a good fit for that: the key is the item's name, and the value is how many times it was ordered.

orders = ["coffee with milk", "sweet tea", "coffee with milk", "toast", "coffee with milk"]
counts = {}
for item in orders:
    counts[item] = counts.get(item, 0) + 1
print(counts)   # {'coffee with milk': 3, 'sweet tea': 1, 'toast': 1}

This table follows the loop, one pass per row:

item counts.get(item, 0) counts afterwards
coffee with milk 0 {'coffee with milk': 1}
sweet tea 0 {'coffee with milk': 1, 'sweet tea': 1}
coffee with milk 1 {'coffee with milk': 2, 'sweet tea': 1}
toast 0 {'coffee with milk': 2, 'sweet tea': 1, 'toast': 1}
coffee with milk 2 {'coffee with milk': 3, 'sweet tea': 1, 'toast': 1}

There are three ways to count:

A Counter example (the from ... import line is covered in the lesson Modules & Imports):

from collections import Counter

orders = ["coffee with milk", "sweet tea", "coffee with milk", "toast", "coffee with milk"]
counts = Counter(orders)
print(counts)                 # Counter({'coffee with milk': 3, 'sweet tea': 1, 'toast': 1})
print(counts.most_common(1))  # [('coffee with milk', 3)]

.most_common(1) gives the one item ordered most often, with its count, as a pair inside a list.

⚠️ Keys that are misspelt, missing, or looked for in the wrong place

TL;DR: A dictionary stores key: value pairs (a name and its value) inside { }, and menu["sweet tea"] reads a value through its key. menu[key] = value adds a new key at the end, or replaces an existing key's value without moving it. del menu[key] deletes that pair. Reading a missing key with square brackets gives a KeyError, while .get(key, default) returns the default: when there is no email key, data.get("email", "unknown") gives unknown. for name, price in menu.items(): goes through the pairs in the order they were added. To count how many times each item appears, use counts[item] = counts.get(item, 0) + 1.

⚡ Look it up by name

Write:

menu = {"coffee with milk": 15, "sweet tea": 5, "toast": 12}

print(menu["sweet tea"])     # 5
Guess first: what does 15 in menu give?

False. in checks the keys (the names left of the colons), not the values (what is right of them). The one that is True is "coffee with milk" in menu.

Meaning: A dictionary stores key: value pairs inside { }. A value is read through its key, as in menu["sweet tea"], not through a position number.

⚡ Add or replace

Write:

menu = {"coffee with milk": 15, "sweet tea": 5, "toast": 12}
menu["iced orange"] = 8     # a new key: added
menu["sweet tea"] = 6       # an existing key: its value is replaced
del menu["toast"]           # delete the key and its value

Meaning: menu[key] = value adds a new pair when the key isn't there yet, and replaces the value when the key is already there. Keys must be unique.

⚡ A key that isn't there

Meaning: If menu has no iced orange key yet, menu["iced orange"] gives KeyError: 'iced orange'. When a key might be missing, use .get(): menu.get("iced orange", 0) gives the 0 you wrote as a replacement, with no error.

⚡ Key and value together

Write:

menu = {"coffee with milk": 15, "sweet tea": 5, "toast": 12}
for name, price in menu.items():
    print(f"{name}: {price}")
Guess first: without .items(), does for name, price in menu: work?

No: ValueError: too many values to unpack (expected 2). Without .items(), the loop gives only the keys, and one key's text cannot be unpacked into name and price.

Meaning: .items() gives the (key, value) pairs one at a time, and name, price unpacks each pair into two variables.

What you will learn