PythonMastery

Nested dictionary in Python

Store a dictionary inside a dictionary, read a value two levels down, change it, and avoid a KeyError when a key may be missing.

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 mobile

How it 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.

Learn the idea: Dictionaries