Lesson 13
Nested Dictionaries and Collection Combinations
Model real-world records using nested dictionaries and combine dictionaries with lists, tuples, and sets safely.
What you will learn
Create dictionaries inside dictionaries · Store lists, tuples, and sets as dictionary values · Access and update multi-level data · Know which collection combinations are valid
Model real-world records using nested dictionaries and combine dictionaries with lists, tuples, and sets safely.
| Skill | Real-world use |
|---|---|
| Nested dicts | Student records, API JSON |
| Mixed values | Tags (set), scores (list), coords (tuple) |
| List of dicts | Tables, API arrays |
| Valid combinations | Avoid TypeError: unhashable |
After File 12 — Dictionary Methods, you can read, update, and iterate flat dictionaries. This lesson stacks collections inside each other — the pattern behind most JSON data.
Learning roadmap
1. Nested dictionary (dict inside dict)
A nested dictionary is simply a dictionary whose values are themselves dictionaries. This is one of the most common ways to represent structured data like students, employees, or API responses.
Think of the outer dictionary as a student record and the inner dictionaries as grouped mark sheets.
student = {
"sno": 10,
"sname": "RS",
"IntMarks": {
"cm": 17,
"cpp": 16,
"os": 19
},
"ExtMarks": {
"cm": 78,
"cpp": 77,
"os": 79
}
}
print(student["IntMarks"]["cm"]) # 17Memory shortcut
Access nested values one level at a time:
Outer Key → Inner Key → Value
Example: student["IntMarks"]["cpp"]
2. Updating nested dictionaries
Since the inner object is still a dictionary, it remains mutable.
Add a new subject
student["IntMarks"]["DBMS"] = 16
student["ExtMarks"]["DBMS"] = 74
print(student["IntMarks"])Modify an existing value
student["IntMarks"]["os"] = 20
print(student["IntMarks"]["os"]) # 20Delete a nested key
student["IntMarks"].pop("cm")
print(student["IntMarks"])The outer dictionary stays the same; only the inner dictionary changes.
3. Iterating through nested data
Loop through the outer dictionary first, then the inner dictionary when needed.
for key, value in student.items():
print(key, "→", value)
print("----- Internal Marks -----")
for subject, mark in student["IntMarks"].items():
print(subject, mark)Expected output:
sno → 10
sname → RS
IntMarks → {'cm': 17, 'cpp': 16, 'os': 19}
ExtMarks → {'cm': 78, 'cpp': 77, 'os': 79}
----- Internal Marks -----
cm 17
cpp 16
os 19Use .get() for optional nested sections:
for subj, mark in student.get("IntMarks", {}).items():
print(subj, mark)4. Dictionary with other collections
A dictionary can store almost any Python object as its value.
A. List as a dictionary value
Use lists when the data grows or changes order.
student = {
"marks": [85, 90, 78]
}
student["marks"].append(92)
student["marks"].sort(reverse=True)
print(student)
# {'marks': [92, 90, 85, 78]}B. Tuple as a dictionary value
Use tuples for fixed data like coordinates.
location = {
"coords": (17.3850, 78.4867)
}
print(location["coords"][0]) # Latitude
location["coords"] = (18.0, 79.0) # Reassign entire tupleYou cannot modify an individual tuple element because tuples are immutable. Reassign the whole tuple instead.
C. Set as a dictionary value
Great for storing unique subjects, skills, or tags.
student = {
"subjects": {"Math", "Physics", "Chemistry"}
}
student["subjects"].add("Biology")
print(student)Duplicate values are automatically ignored.
5. Dictionary inside lists and tuples
This pattern appears frequently in JSON APIs.
List of dictionaries
students = [
{"id": 1, "name": "Asha"},
{"id": 2, "name": "Ravi"}
]
students[0]["name"] = "Anil"
print(students)Think of this as a table:
| ID | Name |
|---|---|
| 1 | Anil |
| 2 | Ravi |
Tuple containing a dictionary
record = (100, {"x": 1})
record[1]["y"] = 2
print(record) # (100, {'x': 1, 'y': 2})Important: The tuple is immutable, but the dictionary inside it is still mutable.
6. Which combinations are valid?
The deciding rule is hashability.
Hashable objects can become dictionary keys or set elements. Lists, sets, and dictionaries are mutable, so they are not hashable.
| Inner → Outer | List | Tuple | Set | Dict Value |
|---|---|---|---|---|
| Dictionary | ✅ | ✅ | ❌ | ✅ |
| List | ✅ | ✅ | ❌ | ✅ |
| Set | ✅ | ✅ | ❌ | ✅ |
| Tuple | ✅ | ✅ | ✅* | ✅ |
*A tuple can be inside a set only if every element inside that tuple is hashable.
Invalid example
my_set = {{1: 2}} # TypeErrorWhy?
- Sets require hashable elements
- Dictionaries are mutable
- Mutable objects are not hashable
Full rules: File 14 — Hashability and Mixed Collections.
Mini project — employee database
Design a real nested record with departments.
employees = {
"E101": {
"name": "Asha",
"dept": {
"id": "D1",
"title": "Engineer"
}
}
}
employees["E101"]["dept"]["title"] = "Senior Engineer"
employees["E102"] = {
"name": "Ravi",
"dept": {
"id": "D2",
"title": "Analyst"
}
}
print(employees["E101"]["name"])
print(employees["E102"]["dept"]["title"])Output:
Asha
AnalystRevision cheatsheet
| Task | Syntax |
|---|---|
| Add nested value | d["marks"]["os"] = 20 |
| Read nested value | d["marks"]["cm"] |
| Remove nested key | d["marks"].pop("cm") |
| Loop nested dict | for k, v in d["marks"].items() |
| List value | d["list"].append(x) |
| Set value | d["set"].add(x) |
| Tuple value | Reassign whole tuple only |
Common interview mistakes
Mistake 1 — treating nested dict like a list:
# Wrong — IntMarks is a dict, not a list
# d["IntMarks"].append("DBMS")
d["IntMarks"]["DBMS"] = 18 # correctMistake 2 — nesting a dict inside a set:
# TypeError: unhashable type: 'dict'
# bad = {{1: 2}}Mistake 3 — assuming tuple with dict is set-safe:
# TypeError — dict inside tuple makes tuple unhashable
# s = {(100, {"x": 1})}
s = {(100, frozenset({1}))} # OK — all elements hashableMistake 4 — shallow copy of nested dict:
import copy
original = {"marks": {"cm": 17}}
safe = copy.deepcopy(original)Practice questions
Test yourself before File 14 — Hashability:
- How do you read the internal mark for
cmfrom a student record? - How do you add a new subject
DBMStoIntMarks? - Can a dictionary be an element inside a set?
- Can you mutate a dict that lives inside a tuple?
- What pattern models a table of student rows in Python?
Knowledge check
Q1: How do you add a new subject to IntMarks?
Answer: d["IntMarks"]["DBMS"] = 18 — not .append() (dict) or .add() (wrong object).
Q2: Can a tuple containing a dictionary be a set element?
Answer: No — the dict is unhashable, so the tuple cannot be hashed either.
Q3: Is { {1, 2} } valid?
Answer: No — sets require hashable elements; use { frozenset({1, 2}) }.
Q4: Can you change record[1]["y"] when record = (100, {"x": 1})?
Answer: Yes — the inner dict is mutable even though the tuple shell is not.
Q5: Best structure for many similar records (API / table)?
Answer: List of dictionaries — [{"id": 1, "name": "Asha"}, ...].
Interview takeaways
- Nested dictionaries model structured entities like students, employees, and API JSON.
- Dictionary values can be lists, tuples, sets, or other dictionaries.
- Mutability belongs to the inner object: a tuple can contain a mutable dictionary.
- Hashability determines whether something can become a dictionary key or set element.
Loading playground…