Quick Overview
`d["key"]` raises `KeyError` when the key is absent; `d.get("key")` returns `None` instead. Which you want depends on whether a missing key is a bug or an expected case.
Create a function city_facts(city) that receives a dictionary containing name, population, and continent keys, and returns a formatted sentence string like: "Paris has a population of 2,140,526 and is situated in Europe".
Extracting object attributes and formatting summary strings is a daily task when building API backends, summary reports, and UI cards.
Extract key values and format using f-strings:
def city_facts(city):
name = city["name"]
population = city["population"]
continent = city["continent"]
return f"{name} has a population of {population} and is situated in {continent}"
# Testing our function
print(city_facts({
"name": "Paris",
"population": "2,140,526",
"continent": "Europe"
}))
# Output: "Paris has a population of 2,140,526 and is situated in Europe"
print(city_facts({
"name": "Tokyo",
"population": "13,929,286",
"continent": "Asia"
}))
# Output: "Tokyo has a population of 13,929,286 and is situated in Asia"
You can also read dictionary keys directly inside f-string brackets:
def city_facts_inline(city):
return f"{city['name']} has a population of {city['population']} and is situated in {city['continent']}"
f"..."), use single quotes for internal dictionary keys (city['name']). Mixing double quotes inside double quotes causes syntax errors!Use clean f-strings for dictionary summary formatting. Next, let's finish our Python practice track with Nested List Verification!
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.