Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In production backend engineering, data rarely exists as flat key-value pairs. User profiles contain contact addresses, e-commerce orders hold arrays of line items with nested seller details, and cloud APIs exchange deeply nested JSON payloads.
In Python, a nested dictionary is simply a dictionary where one or more values are themselves dictionaries. Combining nested dictionaries allows you to represent complex tree structures, relational models, and document databases natively.
How data and code flow step-by-step
You can drill down into nested dictionaries by chaining square brackets [key1][key2][key3]:
.get() & Safe AccessDirect bracket chaining (d["a"]["b"]["c"]) raises a fatal KeyError if any intermediate branch key is absent. Use chained .get() calls with empty fallback dictionaries:
To inspect or process multi-tier structures:
To flatten a multi-tier dictionary into a single-level dictionary with compound keys (e.g. for database export or CSV conversion):
How data and code flow step-by-step
How data and code flow step-by-step
| Scenario | ❌ Anti-Pattern | ✅ Pythonic Idiom |
|---|---|---|
| Deep Lookup | d[k1][k2][k3] on untrusted API data | d.get(k1, {}).get(k2, {}).get(k3, default) |
| Deep Cloning | clone = nested_d.copy() | import copy; clone = copy.deepcopy(nested_d) |
| Add New Sub-Category | Assigning d[k1][k2] = val when k1 doesn't exist | d.setdefault(k1, {})[k2] = val |
| Looping Keys & Values | for k in d: for k2 in d[k]: | for k, sub_dict in d.items(): for sub_k, v in sub_dict.items(): |
+---------------------------------------------------------------------------+
| NESTED DICTIONARY CHEAT SHEET |
+---------------------------------------------------------------------------+
| Pattern | Explanation / Syntax |
|--------------------------+------------------------------------------------|
| 2D Coordinate Access | dict[outer_key][inner_key] |
| Deep Mutation | dict[outer_key][inner_key] = new_val |
| Safe Chained Fallback | d.get("k1", {}).get("k2", {}).get("k3", def) |
| Deep In-Place Init | d.setdefault("k1", {})["k2"] = val |
| Full Recursive Copy | copy.deepcopy(nested_dict) |
| Iteration | for outer_k, inner_dict in d.items(): |
+---------------------------------------------------------------------------+Accessing dict[key] directly raises a KeyError if the key is missing. Use .get() instead:
Keys must be hashable and immutable. Lists cannot be used as keys, but tuples can:
data["user"]["address"]["city"] raise if the "address" key is missing?A. AttributeError B. KeyError: 'address' C. IndexError D. Returns None
city from user without raising a KeyError if any intermediate parent is missing?A. user.fetch("address.city") B. user.get("address", {}).get("city", "Default City") C. user["address"]?.["city"] D. user.search("city")
d.setdefault("config", {})["timeout"] = 30 accomplish?A. It raises a SyntaxError B. If "config" does not exist, it initializes it as an empty dictionary {} and then assigns {"timeout": 30} inside it C. It deletes the "config" key D. It resets all values in d to 30
A. 1 B. 2 C. 3 D. KeyError
copy.deepcopy() necessary when duplicating nested dictionaries?A. Regular .copy() only clones the top-level keys; inner dictionaries remain shared references that mutate simultaneously B. Python will not run without it C. Nested dictionaries cannot be printed without deepcopy D. Deepcopy converts dictionaries into tuples
Build a healthcare patient management system for an Indian hospital. Each patient record is stored as a nested dictionary: {"patient_id": {"vitals": {"bp": ..., "spo2": ...}, "prescriptions": [...], "assigned_doctor": ...}}. Write functions to admit a new patient, record updated vitals, safely check oxygen saturation (spo2) with defensive fallback, prescribe an additional medicine, and print a formatted patient chart.
In the next lesson, we will continue your Python learning journey with Project: Student Records (11: Dictionaries).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Dictionary Methods | Project: Student Records |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.