How to Access Nested Dictionary in Python: Simple Guide
To access a value in a nested dictionary in Python, use multiple
[key] lookups in sequence, like dict[key1][key2]. Each [key] accesses a deeper level inside the dictionary structure.Syntax
Use square brackets [] with keys to access dictionary values. For nested dictionaries, chain these lookups for each level.
dict[key1]: Accesses the first-level value.dict[key1][key2]: Accesses the second-level value inside the nested dictionary.- Continue chaining for deeper levels.
python
nested_dict = {'a': {'b': {'c': 42}}}
value = nested_dict['a']['b']['c']Example
This example shows how to access a value inside a nested dictionary with three levels.
python
person = {
'name': 'Alice',
'contact': {
'email': 'alice@example.com',
'phone': {
'home': '123-4567',
'work': '987-6543'
}
}
}
# Access nested phone number
home_phone = person['contact']['phone']['home']
print(home_phone)Output
123-4567
Common Pitfalls
Trying to access a key that does not exist will cause a KeyError. To avoid this, use the .get() method or check if the key exists before accessing.
Also, be careful with the order of keys; each must match the dictionary structure exactly.
python
data = {'x': {'y': 10}}
# Wrong way: causes KeyError if key missing
# print(data['x']['z'])
# Right way: use get with default
print(data.get('x', {}).get('z', 'Not found'))Output
Not found
Quick Reference
| Operation | Description | Example |
|---|---|---|
| Access nested value | Use chained keys in brackets | dict['key1']['key2'] |
| Safe access | Use get() with default to avoid errors | dict.get('key1', {}).get('key2', default) |
| Check key exists | Use 'in' keyword before access | 'key1' in dict and 'key2' in dict['key1'] |
Key Takeaways
Access nested dictionary values by chaining keys with square brackets.
Use .get() method to safely access keys that might not exist.
Always match the key order to the dictionary's nested structure.
Check for key existence to prevent KeyError exceptions.
Practice with examples to understand nested dictionary access clearly.