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
over_budget with two parameters: prices (a dictionary of item names to prices) and limit.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.
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))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.