A dictionary value can be another dictionary. This is a nested dictionary, and it is the usual way to store a record that has groups of details, such as an employee and their address.
The program
python
employee = {
"name": "Grace",
"role": "Engineer",
"address": {"city": "London", "postcode": "EC1A 1BB"},
}
print(employee["name"])
print(employee["address"]["city"])
employee["address"]["city"] = "Manchester"
print(employee["address"])
print(employee.get("salary", "Not set"))
print(employee.get("phone", {}).get("mobile", "No mobile"))output
Grace
London
{'city': 'Manchester', 'postcode': 'EC1A 1BB'}
Not set
No mobileHow it works
employee["address"]gives the inner dictionary. Adding["city"]after it reads a key from that inner dictionary.- The same chain on the left of
=changes the inner value. employee["salary"]would raise aKeyError, because there is no such key.get("salary", "Not set")returns the default instead.- For a key that may be missing two levels down,
get("phone", {})returns an empty dictionary whenphoneis missing, so the second.get()still works.
Looping over nested data
python
team = {
"Ada": {"age": 36, "city": "London"},
"Linus": {"age": 28, "city": "Helsinki"},
"Hedy": {"age": 41, "city": "Vienna"},
}
for name, info in team.items():
print(f"{name} is {info['age']} and lives in {info['city']}")output
Ada is 36 and lives in London Linus is 28 and lives in Helsinki Hedy is 41 and lives in Vienna
Inside the f-string, the keys use single quotes because the f-string itself uses double quotes.