Looping Over Dictionaries

Looping Over Dictionaries

A for loop over a dictionary visits its keys:

prices = {"apple": 4, "bread": 32, "milk": 21}
for item in prices:
    print(item)

Output:

apple
bread
milk

Entries come out in the order they were added.

To get keys and values together, loop over .items() with two loop variables:

for item, price in prices.items():
    print(f"{item} costs {price}")

Output:

apple costs 4
bread costs 32
milk costs 21

.values() gives the values alone — summing them is the accumulator pattern again:

total = 0
for price in prices.values():
    total += price

Exercise

  1. Define a function named over_budget with two parameters: prices (a dictionary of item names to prices) and limit.
  2. It returns a list of the item names whose price is greater than limit, in dictionary order.

over_budget({"apple": 4, "bread": 32, "milk": 21}, 20) returns ["bread", "milk"].

Run your code to see the output, then press Submit.

Tests

import unittest


class TestOverBudget(unittest.TestCase):
    def test_two_items_over_20(self):
        self.assertEqual(
            over_budget({"apple": 4, "bread": 32, "milk": 21}, 20),
            ["bread", "milk"],
        )

    def test_no_items_over_limit(self):
        self.assertEqual(over_budget({"apple": 4}, 100), [])

    def test_price_equal_to_limit_is_not_over(self):
        self.assertEqual(over_budget({"apple": 4}, 4), [])

    def test_empty_dictionary(self):
        self.assertEqual(over_budget({}, 10), [])
def over_budget(prices, limit):
    result = []
    for item, price in prices.items():
        if price > limit:
            result.append(item)
    return result


print(over_budget({"apple": 4, "bread": 32, "milk": 21}, 20))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.