Python for beginners · Lesson 10 of 15

Dictionaries: look things up by name

Store key-value pairs in a dictionary, read values safely with get(), add, change and remove entries, loop over items and count things.

About 16 minutes · code runs in your browser, nothing to install

A list finds items by position. A dictionary (dict) finds them by name. It stores pairs of a key and a value, like a phone book stores a name and a number. You write it with curly braces, a colon between each key and its value, and commas between pairs.

Pythoneditable
ages = {"Ana": 34, "Ben": 28, "Chloe": 41}
print(ages["Ben"])
print(len(ages))
ages["Dev"] = 25
ages["Ana"] = 35
print(ages)
Output
28
3
{'Ana': 35, 'Ben': 28, 'Chloe': 41, 'Dev': 25}

Assigning to a new key adds a pair; assigning to an existing key replaces its value.

Keys are usually strings or numbers and must be unique. Values can be anything: numbers, strings, lists, even other dictionaries. A dictionary keeps its pairs in the order you added them.

Reading safely with get()

Asking for a key that does not exist with d[key] stops the program with a KeyError. dict.get() returns None instead, or a default value you choose. in checks whether a key is present.

Pythoneditable
prices = {"coffee": 2.5, "tea": 2.0, "cake": 3.75}
print(prices.get("tea"))
print(prices.get("juice"))
print(prices.get("juice", 0))
print("cake" in prices)
print(2.5 in prices)
Output
2.0
None
0
True
False

in looks at the keys only, so 2.5 is not found even though it is one of the values.

Looping over a dictionary

Looping over a dictionary gives you its keys. dict.items() gives you key and value together, and dict.values() just the values.

Pythoneditable
stock = {"pens": 40, "notebooks": 12, "folders": 0}
for item in stock:
    print(item)
for item, count in stock.items():
    print(f"{item}: {count}")
print("Total items:", sum(stock.values()))
Output
pens
notebooks
folders
pens: 40
notebooks: 12
folders: 0
Total items: 52

Removing entries

del d[key] deletes a pair. dict.pop() deletes it and gives you the value back.

Pythoneditable
cart = {"apples": 3, "bread": 1, "milk": 2}
del cart["bread"]
removed = cart.pop("milk")
print(removed)
print(cart)
Output
2
{'apples': 3}

Counting with a dictionary

One of the most useful patterns in Python: count how often each thing appears. get(key, 0) returns 0 the first time a key is seen, so you can always add 1.

Pythoneditable
votes = ["red", "blue", "red", "green", "red", "blue"]
counts = {}
for color in votes:
    counts[color] = counts.get(color, 0) + 1
print(counts)
for color, n in counts.items():
    print(f"{color}: {n} vote(s)")
Output
{'red': 3, 'blue': 2, 'green': 1}
red: 3 vote(s)
blue: 2 vote(s)
green: 1 vote(s)
Tip: A list of dictionaries is a simple way to store a table: each dictionary is one row, such as {"name": "Ana", "city": "Porto"}, and you loop over the list to read every row.

✎ Exercise

Count how many times each word appears in sentence and print the dictionary. Then print how many times the appears, as the appears 3 times (take the number from the dictionary).

Hint: Split the sentence into words, loop over them and use counts.get(word, 0) + 1.

Your codewrite your answer, then Run
sentence = "the cat and the dog and the bird"
counts = {}
# your code here

Expected output:

{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
the appears 3 times
Show a solution
Solutioneditable
sentence = "the cat and the dog and the bird"
counts = {}
for word in sentence.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)
print("the appears", counts["the"], "times")
Output
{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
the appears 3 times

Check yourself

1. What does {"a": 1}.get("b", 5) return?

2. What does "tea" in prices check?

3. What happens with d["x"] = 10 if d already has the key "x"?

Spotted a mistake on this page? Tell us