Home › Learn › Python › Dictionaries, tuples, and sets

Looping over dictionaries

Lesson 22 of 40. Visit keys, values, or both.

Looping over a dictionary gives its keys: for k in d:. d.values() gives the values and d.items() gives (key, value) pairs, which unpack straight into two loop variables: for name, price in prices.items():.

To find the entry with the largest value, max(d, key=d.get) returns the key whose value is largest; the same works with min. It reads oddly the first time: max walks the keys, and d.get turns each key into the value to compare.

prices = {"tea": 2.5, "cake": 4}
for item, price in prices.items():
    print(item, price)
print(max(prices, key=prices.get))   # cake

Your task

Write total_value(prices, quantities) that returns the sum of price times quantity for every item in prices, treating items missing from quantities as zero. Then write most_expensive(prices) that returns the name of the item with the highest price.

Hint 1

for item, price in prices.items(): total += price * quantities.get(item, 0)

Hint 2

max(prices, key=prices.get)

Show the solution
def total_value(prices, quantities):
    total = 0
    for item, price in prices.items():
        total += price * quantities.get(item, 0)
    return total


def most_expensive(prices):
    return max(prices, key=prices.get)

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.