Going through a dictionary
A for loop over a dictionary goes through its keys, in the order they were added. Each key gives you its value:
stock = {"apples": 5, "pears": 0, "plums": 7}
for fruit in stock:
print(fruit, stock[fruit])
apples 5
pears 0
plums 7When you need both the key and the value, the method items() gives them in pairs. The loop then has two variables, separated by a comma: the first one gets the key and the second one the value.
stock = {"apples": 5, "pears": 0, "plums": 7}
for fruit, amount in stock.items():
if amount == 0:
print(f"{fruit}: sold out")
else:
print(f"{fruit}: {amount} left")
apples: 5 left
pears: sold out
plums: 7 leftHow one pair can fill two variables is explained in the tuples module at the end of this part.
A loop may change the values of keys that are already there. Adding or removing keys during the loop is another matter, which the step on removing keys comes back to.
stock = {"apples": 5, "pears": 0, "plums": 7}
for fruit in stock:
stock[fruit] += 10
print(stock)
{'apples': 15, 'pears': 10, 'plums': 17}In alphabetical order
sorted works on a dictionary too: it returns a list of its keys, in order. Looping over that list goes through the dictionary in alphabetical order:
phone_book = {"Max": "555-0199", "Ada": "555-0123", "Lin": "555-0150"}
print(sorted(phone_book))
for name in sorted(phone_book):
print(name, phone_book[name])
['Ada', 'Lin', 'Max']
Ada 555-0123
Lin 555-0150
Max 555-0199The best pair
Finding the largest value works as it does with a list, except that you usually want to remember the key that goes with it:
votes = {"pizza": 12, "tacos": 17, "sushi": 9}
winner = ""
most = 0
for food, count in votes.items():
if count > most:
winner = food
most = count
print(f"{winner} won with {most} votes")
tacos won with 17 votes