Checking Keys

Checking Keys

in checks whether a key exists in a dictionary:

prices = {"apple": 4, "bread": 32}
print("apple" in prices)
print("cheese" in prices)

Output:

True
False

in looks at keys only, never values.

The get method reads a key like square brackets do, but instead of raising KeyError for a missing key it returns a fallback. The fallback is its second argument, or None without one:

print(prices.get("apple", 0))
print(prices.get("cheese", 0))
print(prices.get("cheese"))

Output:

4
0
None

Use square brackets when a missing key is a bug you want to hear about. Use get when missing keys are normal.

Exercise

  1. Define a function named unit_price with two parameters: prices (a dictionary) and item. It returns the price, or 0 when the item is not listed.
  2. Define a function named is_stocked with two parameters: stock (a dictionary of counts) and item. It returns True when item is a key in stock and its count is greater than 0.

is_stocked({"milk": 0}, "milk") returns False.

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

Tests

import unittest


class TestCheckingKeys(unittest.TestCase):
    def test_unit_price_of_a_listed_item(self):
        self.assertEqual(unit_price({"apple": 4}, "apple"), 4)

    def test_unit_price_of_a_missing_item_is_0(self):
        self.assertEqual(unit_price({"apple": 4}, "cheese"), 0)

    def test_stocked_item(self):
        self.assertIs(is_stocked({"milk": 0, "bread": 3}, "bread"), True)

    def test_item_with_zero_count_is_not_stocked(self):
        self.assertIs(is_stocked({"milk": 0}, "milk"), False)

    def test_missing_item_is_not_stocked(self):
        self.assertIs(is_stocked({"milk": 2}, "cheese"), False)
def unit_price(prices, item):
    return prices.get(item, 0)


def is_stocked(stock, item):
    return item in stock and stock[item] > 0


print(unit_price({"apple": 4}, "apple"))
print(unit_price({"apple": 4}, "cheese"))
print(is_stocked({"milk": 0, "bread": 3}, "bread"))
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.