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.
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.
ages = {"Ana": 34, "Ben": 28, "Chloe": 41}
print(ages["Ben"])
print(len(ages))
ages["Dev"] = 25
ages["Ana"] = 35
print(ages)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.
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)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.
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()))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.
cart = {"apples": 3, "bread": 1, "milk": 2}
del cart["bread"]
removed = cart.pop("milk")
print(removed)
print(cart)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.
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)"){'red': 3, 'blue': 2, 'green': 1}
red: 3 vote(s)
blue: 2 vote(s)
green: 1 vote(s){"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.
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 timesShow a solution
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"){'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}
the appears 3 timesCheck yourself
1. What does {"a": 1}.get("b", 5) return?
The key "b" is missing, so get() returns the default you gave: 5.
2. What does "tea" in prices check?
in on a dictionary looks only at the keys.
3. What happens with d["x"] = 10 if d already has the key "x"?
Keys are unique, so assigning to an existing key replaces its value.