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
- A dictionary is written in curly braces
{ }. Each entry is akey: valuepair, with commas between the pairs. - The key is the name you look up, usually text. The value is what is stored for that key, and it can be of any type. On the price list, the key is the item's name and the value is its price.
menu["sweet tea"]reads a value through its key. The square brackets look like a list index, but they hold a key, not a number.menu[0]does not mean "the first one". It givesKeyError: 0, because there is no key0.len(menu)counts the pairs: 3.inchecks the keys, not the values. So15 in menuisFalse.- Keys must be unique. If the same key is written twice, only the last one stays:
{"coffee with milk": 15, "coffee with milk": 18}becomes{'coffee with milk': 18}.
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} |
menu[key] = valuedoes two jobs. If the key is not there yet, a new pair is added. If the key is already there, its value is replaced.- A dictionary keeps its keys in the order they were added. A new key goes at the end. Replacing a value does not move the key:
sweet teastays second. del menu[key]deletes the pair.menu.pop("iced orange")also deletes the pair, and it returns the value,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
.get(key)returnsNonewhen the key is missing, with no error..get(key, default)returnsdefaultwhen the key is missing. For example, withdata = {"name": "Rina", "age": 25},data.get("email", "unknown")givesunknown.- When the key is there, the default is ignored:
menu.get("sweet tea", 0)is still5.
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
.items()gives the(key, value)pairs one at a time.name, priceunpacks each pair into two variables: the key intoname, the value intoprice.- The order is the order in which the keys were added.
for name in menu:gives only the keys.menu.keys()holds every key, andmenu.values()holds every value. For example,sum(menu.values())is32.
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} |
counts = {}is an empty dictionary.counts.get(item, 0)gives 0 for an item that appears for the first time, or its count so far if it has appeared before. Then 1 is added to that result, and the new number is stored incounts[item].- In this lesson's exercise, you count the words in a text. Split the text into a list of words first with
.split()from the string lesson:"coffee tea coffee".split()gives['coffee', 'tea', 'coffee'].
There are three ways to count:
.get(item, 0) + 1(the way above): you see for yourself how each count goes up. That is why this lesson uses it.Counterfrom the built-incollectionsmodule: counts everything in one line. Good for everyday code.defaultdict(int), also fromcollections: a key that does not exist yet starts at 0 automatically, socounts[item] += 1works right away, with noKeyError.
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
- Adding to a key that isn't there yet.
counts[item] += 1on an empty dictionary fails withKeyError: 'coffee with milk', because there is no number yet to add to. Usecounts.get(item, 0) + 1. - A wrong letter in the key.
menu["Coffee with milk"]givesKeyError: 'Coffee with milk'. For Python,Coffee with milkandcoffee with milkare two different keys. - Forgetting
.items().for name, price in menu:fails withValueError: too many values to unpack (expected 2), because without.items()the loop gives only the keys, and one key's text cannot be unpacked into two names. - Looking for a value with
in.15 in menuisFalseeven though one item costs 15. To look for a value, use15 in menu.values().
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.