Nested Dictionaries
Python · Dictionaries
Theory
A nested dictionary is a dict whose values are themselves dicts (or lists of dicts). employees = {'e1': {'name': 'Asha', 'dept': 'IT'}} maps an employee ID to a whole record. You reach inner values by chaining square brackets, each one applied to the result of the previous: employees['e1'] returns the inner dict, and employees['e1']['dept'] returns 'IT'. Assigning works the same way: employees['e1']['dept'] = 'HR' changes the inner dict in place.
This is exactly the shape of JSON, so data from APIs or json.load() usually arrives as nested dicts and lists. Two gotchas: if any key along the path is missing you get KeyError, so chain .get() with a default dict (employees.get('e9', {}).get('dept')) for optional data. And copying the outer dict with .copy() is shallow: the copy still shares the same inner dicts, so changing one changes both; use copy.deepcopy() for a fully independent copy.
Why we use it
Real data is hierarchical: an employee has an address, an order has line items, an API response has nested sections. Nested dicts model that structure naturally without flattening everything into one level.
When to use it
Use nested dicts for JSON-like, hierarchical data and records grouped by ID. When the data is really a table (same fields for every record) and you need filtering or aggregation, convert it to a pandas DataFrame with pd.DataFrame or pd.json_normalize.
How it works
- Evaluate employees['e1']['dept']
- Look up 'e1' in the outer dict
- Is 'e1' a key? Yes: Get the inner dict {'name': 'Asha', 'dept': 'IT'}. No: Raise KeyError: 'e1'.
- Look up 'dept' in that inner dict
- Return 'IT'
Syntax
{"outer_key": {"inner_key": "value"}}Example
employees = {'e1': {'name': 'Asha', 'dept': 'IT'}}
employees['e1']['dept']Key points
- Mirrors JSON structure closely
- Access with chained square brackets: d['e1']['dept']
- A missing key at any level raises KeyError
- Chain .get() for optional paths: d.get('e9', {}).get('dept')
- .copy() is shallow: inner dicts stay shared; use copy.deepcopy()