Python Arena
Step 3 of 6

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])
Output
apples 5
pears 0
plums 7

When 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")
Output
apples: 5 left
pears: sold out
plums: 7 left

How 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)
Output
{'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])
Output
['Ada', 'Lin', 'Max']
Ada 555-0123
Lin 555-0150
Max 555-0199

The 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")
Output
tacos won with 17 votes

Your task

Challenge 1 of 3

Fill in the blanks so the program prints each name with as many stars as the grade:

Ada *****
Max ***
Lin ****

Challenge 2

Write a function best_student(grades) that takes a dictionary of names and grades and returns the name with the highest grade. If several students share the highest grade, it returns the one that comes first in the dictionary. Grades are whole numbers from 1 to 5.

For example, best_student({"Ada": 4, "Max": 3, "Lin": 5}) returns "Lin".

Challenge 3

A shop keeps its stock in a dictionary of products and amounts. Write a function running_low(stock, limit) that returns a list of the products whose amount is less than limit, in alphabetical order.

For example, running_low({"pens": 3, "clips": 50, "tape": 1}, 5) returns ['pens', 'tape'].