Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 13

Nested Dictionaries and Collection Combinations

Model real-world records using nested dictionaries and combine dictionaries with lists, tuples, and sets safely.

Intermediate28 min

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

Nested dict values list of dicts hash rules 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.

Student record with IntMarks and ExtMarks inner dicts

Think of the outer dictionary as a student record and the inner dictionaries as grouped mark sheets.

python
student = {
    "sno": 10,
    "sname": "RS",
    "IntMarks": {
        "cm": 17,
        "cpp": 16,
        "os": 19
    },
    "ExtMarks": {
        "cm": 78,
        "cpp": 77,
        "os": 79
    }
}

print(student["IntMarks"]["cm"])   # 17

Memory shortcut

Access nested values one level at a time:

Outer Key to Inner Key to Value access path

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

python
student["IntMarks"]["DBMS"] = 16
student["ExtMarks"]["DBMS"] = 74

print(student["IntMarks"])

Modify an existing value

python
student["IntMarks"]["os"] = 20

print(student["IntMarks"]["os"])   # 20

Delete a nested key

python
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.

python
for key, value in student.items():
    print(key, "→", value)

print("----- Internal Marks -----")

for subject, mark in student["IntMarks"].items():
    print(subject, mark)

Expected output:

text
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 19

Use .get() for optional nested sections:

python
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.

list tuple set dict as dictionary value types

A. List as a dictionary value

Use lists when the data grows or changes order.

python
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.

python
location = {
    "coords": (17.3850, 78.4867)
}

print(location["coords"][0])     # Latitude

location["coords"] = (18.0, 79.0)    # Reassign entire tuple

You 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.

python
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

List of dictionaries as table rows
python
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

Immutable tuple shell with mutable inner dict
python
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.

TypeError unhashable dict when nesting dict in set
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

python
my_set = {{1: 2}}      # TypeError

Why?

  • 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.

Employee database E101 E102 nested dept records
python
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:

text
Asha
Analyst

Revision 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:

python
# Wrong — IntMarks is a dict, not a list
# d["IntMarks"].append("DBMS")
d["IntMarks"]["DBMS"] = 18   # correct

Mistake 2 — nesting a dict inside a set:

python
# TypeError: unhashable type: 'dict'
# bad = {{1: 2}}

Mistake 3 — assuming tuple with dict is set-safe:

python
# TypeError — dict inside tuple makes tuple unhashable
# s = {(100, {"x": 1})}
s = {(100, frozenset({1}))}   # OK — all elements hashable

Mistake 4 — shallow copy of nested dict:

python
import copy
original = {"marks": {"cm": 17}}
safe = copy.deepcopy(original)

Practice questions

Test yourself before File 14 — Hashability:

  1. How do you read the internal mark for cm from a student record?
  2. How do you add a new subject DBMS to IntMarks?
  3. Can a dictionary be an element inside a set?
  4. Can you mutate a dict that lives inside a tuple?
  5. 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…