Nested Address Lookup

Medium ⏱ 12 min 62% acceptance ★★★★☆ 4.3
Write a function get_city(record) where record is a dict shaped like {"name": ..., "address": {"street": ..., "city": ..., "zip": ...}}. Return the value at record["address"]["city"]. If the "address" key or the "city" key is missing, return "Unknown".

Examples

Example 1
Input
get_city({'name': 'Ravi', 'address': {'city': 'Pune'}})
Output
'Pune'
Explanation

Nested lookup succeeds.

Example 2
Input
get_city({'name': 'Ravi'})
Output
'Unknown'
Explanation

No address key at all.

Constraints

  • Never raise KeyError even for deeply missing keys.

Topics

Dictionariesnested dicts

Companies

AmazonDeloitte

Hints

Hint 1

Chain `.get()` calls: `record.get("address", {}).get("city", "Unknown")`.

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