Safe Get with a Default

Easy ⏱ 8 min 81% acceptance ★★★★☆ 4.3
Write a function price_of(catalog, item, default=0) that returns catalog[item] if item exists in the dict catalog, otherwise returns default, without raising a KeyError.

Examples

Example 1
Input
price_of({'pen': 10, 'book': 150}, 'book')
Output
150
Explanation

book is present.

Example 2
Input
price_of({'pen': 10}, 'eraser')
Output
0
Explanation

eraser is missing, so the default 0 is returned.

Constraints

  • Do not use try/except.
  • Use the dict `get()` method.

Topics

Dictionariesget()

Companies

AmazonFlipkart

Hints

Hint 1

`dict.get(key, default)` returns default when the key is absent.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.