How to Create Python Nested Dictionaries With a For Loop

To organize related values under group keys in Python, you can build a nested dictionary with a for loop. The loop creates a child dictionary for each group, then adds that group’s fields.

This article shows how to create a child dictionary for each group and retrieve a value using its group and field keys.

TL;DR

Use an outer loop for group keys and make an inner dictionary during each pass. A second loop can fill its fields.

  • Prepare the group names and the values or fields for each group.
  • Assign a fresh empty dictionary to each group before adding child keys.
  • Read or traverse the result by going through the outer mapping before the inner one.

What Is a Python Nested Dictionary?

A nested dictionary stores related details under a group or record key. For a shop, one outer key can select a department and its inner keys can name product counts. Python dictionaries map unique keys to values, and a value may itself be another dictionary.

How to Create a Nested Dictionary With a For Loop

Build one child mapping per outer key, then inspect it with a nested lookup.

Step 1: Prepare the groups and fields

The input has two color names and two size labels. Each outer pass handles one color.

groups = ["red", "blue"]
fields = ["small", "large"]

The inner loop visits both field labels for that color, so you can compare the generated values.

Step 2: Initialize one inner mapping per group

Start with an empty parent dictionary. Put the child initialization inside the outer loop, before writing that group’s fields.

nested = {}
for group in groups:
    nested[group] = {}
    for field in fields:
        nested[group][field] = f"{group}-{field}"

Each pass creates a distinct child object. The value can come from a row or a calculation.

Step 3: Run the example and access a value

Save the complete program as for_loop_demo.py and run python3 for_loop_demo.py. I ran that command and received the following output.

groups = ["red", "blue"]
fields = ["small", "large"]

nested = {}
for group in groups:
    nested[group] = {}
    for field in fields:
        nested[group][field] = f"{group}-{field}"

print(nested)
print(nested["blue"]["large"])
{'red': {'small': 'red-small', 'large': 'red-large'}, 'blue': {'small': 'blue-small', 'large': 'blue-large'}}
blue-large
Terminal shows python3 for_loop_demo.py and the nested dictionary output

The first line prints both records. The last line selects one value by its group and field keys.

Step 4: Traverse both dictionary levels

Call items() at each level when the program must display or transform every key-value pair. The Python tutorial documents items() for visiting a dictionary key and its corresponding value together.

for group, details in nested.items():
    print(group)
    for field, value in details.items():
        print(f"  {field}: {value}")

Step 5: Build from records with different fields

Input rows often provide a group, a field and a value rather than a complete grid. Create a child dictionary only when the first row for that group appears, then write the row’s field.

rows = [
    ("fruit", "apples", 5),
    ("fruit", "pears", 2),
    ("drinks", "tea", 7),
]
stock = {}
for group, item, quantity in rows:
    if group not in stock:
        stock[group] = {}
    stock[group][item] = quantity

print(stock)
{'fruit': {'apples': 5, 'pears': 2}, 'drinks': {'tea': 7}}

Edge Cases When Building Nested Dictionaries

Missing parents, duplicate input and shared mutable values cause frequent surprises when constructing nested data.

Missing parent keys

Direct child assignment on an empty parent produced KeyError: ‘group’ because Python could not find the requested group key.

data = {}
data["group"]["field"] = 1

When groups may be absent, dict.setdefault() returns the existing child mapping or inserts the supplied default. I use it in the loop below because it handles both cases at the assignment point.

data = {}
for group, field, value in [("red", "small", 2), ("blue", "small", 4)]:
    data.setdefault(group, {})[field] = value

print(data)
{'red': {'small': 2}, 'blue': {'small': 4}}

Duplicate group and field pairs

When input repeats the same group and field pair, decide whether the later value should replace the earlier one or both values should be kept. The example below collects repeated values in a list.

events = [("red", "small", 2), ("red", "small", 3)]
counts = {}
for group, field, value in events:
    counts.setdefault(group, {}).setdefault(field, []).append(value)

print(counts)
{'red': {'small': [2, 3]}}

Shared inner dictionaries

Do not put the same mutable child object under several groups unless shared edits are intended.

shared = {}
wrong = {"red": shared, "blue": shared}
wrong["red"]["small"] = 2
print(wrong["blue"])

right = {group: {} for group in ["red", "blue"]}
right["red"]["small"] = 2
print(right["blue"])
{'small': 2}
{}

The first result contains the changed value, while the second child stays empty.

Choosing between setdefault() and defaultdict

Use setdefault() for occasional missing groups. collections.defaultdict(dict) creates absent children automatically.

from collections import defaultdict

auto = defaultdict(dict)
auto["red"]["small"] = 2
print(dict(auto))
{'red': {'small': 2}}

Update and remove nested entries

Once the structure exists, use the same key order to change a field. Deleting a field also requires the parent and child keys to exist, so guard optional data before using del.

if "red" in nested and "small" in nested["red"]:
    del nested["red"]["small"]

nested.setdefault("green", {})["small"] = "green-small"

The membership checks prevent a missing-key exception during deletion. The insertion creates a child for a new group, then writes the selected field into it.

Conclusion

For more examples, see the AskPython Python dictionary tutorial and its guide to Python collections. The official Python dictionary tutorial explains lookup, get() and items().

FAQ

These short answers address common follow-up questions.

How do you access a value in a nested dictionary?

Use the outer key first and the inner key second, as in data[“group”][“field”]. Use get() or a membership check when a key may be absent.

Can a Python dictionary contain another dictionary?

Yes. A dictionary value can be another dictionary, letting an outer key identify a record and inner keys identify its fields.

Why does nested dictionary assignment raise KeyError?

The parent key is missing. Create its child dictionary before assigning a field, or use setdefault() for conditional initialization.

Vignya Durvasula
Vignya Durvasula
Articles: 125