A nested dict is a dictionary within a dictionary. A very simple thing.

Copy>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d['dict1']['innerkey2'] = 'value2'
>>> d
{'dict1': {'innerkey': 'value', 'innerkey2': 'value2'}}

You can also use a defaultdict from the collections package to facilitate creating nested dictionaries.

Copy>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d  # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d)  # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}

You can populate that however you want.

I would recommend in your code something like the following:

Copyd = {}  # can use defaultdict(dict) instead

for row in file_map:
    # derive row key from something 
    # when using defaultdict, we can skip the next step creating a dictionary on row_key
    d[row_key] = {} 
    for idx, col in enumerate(row):
        d[row_key][idx] = col

According to your comment:

may be above code is confusing the question. My problem in nutshell: I have 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also has these columns. i is kind of key columns for these csvs'. j k l column is empty in a.csv but populated in b.csv. I want to map values of j k l columns using 'i` as key column from b.csv to a.csv file

My suggestion would be something like this (without using defaultdict):

Copya_file = "path/to/a.csv"
b_file = "path/to/b.csv"

# read from file a.csv
with open(a_file) as f:
    # skip headers
    f.next()
    # get first colum as keys
    keys = (line.split(',')[0] for line in f) 

# create empty dictionary:
d = {}

# read from file b.csv
with open(b_file) as f:
    # gather headers except first key header
    headers = f.next().split(',')[1:]
    # iterate lines
    for line in f:
        # gather the colums
        cols = line.strip().split(',')
        # check to make sure this key should be mapped.
        if cols[0] not in keys:
            continue
        # add key to dict
        d[cols[0]] = dict(
            # inner keys are the header names, values are columns
            (headers[idx], v) for idx, v in enumerate(cols[1:]))

Please note though, that for parsing csv files there is a csv module.

Answer from Inbar Rose on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-nested-dictionary
Python Nested Dictionary - GeeksforGeeks
July 12, 2025 - A nested dictionary is a dictionary that contains another dictionary as a value. It helps organize complex or grouped data, like student details or product info in a clean and structured way. ... # Creating a Nested Dictionary Dict = { 1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'} }
🌐
W3Schools
w3schools.com › PYTHON › python_dictionaries_nested.asp
Python - Nested Dictionaries
To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary: ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python ...
Discussions

dictionary - How to create nested dictionaries PYTHON - Stack Overflow
This problem is similar to another where I learned How to Create Nested Dictionary in Python with 3 lists How can I achieve an output such from 3 lists that takes the following output form a = ['A'... More on stackoverflow.com
🌐 stackoverflow.com
Dynamically creating nested dictionary from input
Not too too far off, but names[name] = name{}  # this line isn't valid syntax name = {key : value, key : value}  # this would overwrite the string name So just combine them into one like names[name] = {key : value, key : value} Or if you prefer name_d = {key : value, key : value}  # note: new variable name names[name] = name_d More on reddit.com
🌐 r/learnpython
9
6
September 9, 2024
Python nested dictionary
If you want to be able to access sub-dicts without explicitly initialising them, you could use a collections.defaultdict(dict). Otherwise, you'd have to check if the sub-dict exists before initialising it, or use dict.setdefault every time. More on reddit.com
🌐 r/learnpython
3
5
November 24, 2022
Is nested dictionaries bad practise
Whoever told you that nested for loops are bad practice is very probably not a very experienced and skilled programmer. It is possible to traverse a 2 dimensional array without using a nested loop, but the extra math required is definitely harder to read and far more error prone. More on reddit.com
🌐 r/learnprogramming
9
3
November 15, 2022
Top answer
1 of 10
427

A nested dict is a dictionary within a dictionary. A very simple thing.

Copy>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d['dict1']['innerkey2'] = 'value2'
>>> d
{'dict1': {'innerkey': 'value', 'innerkey2': 'value2'}}

You can also use a defaultdict from the collections package to facilitate creating nested dictionaries.

Copy>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d  # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d)  # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}

You can populate that however you want.

I would recommend in your code something like the following:

Copyd = {}  # can use defaultdict(dict) instead

for row in file_map:
    # derive row key from something 
    # when using defaultdict, we can skip the next step creating a dictionary on row_key
    d[row_key] = {} 
    for idx, col in enumerate(row):
        d[row_key][idx] = col

According to your comment:

may be above code is confusing the question. My problem in nutshell: I have 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also has these columns. i is kind of key columns for these csvs'. j k l column is empty in a.csv but populated in b.csv. I want to map values of j k l columns using 'i` as key column from b.csv to a.csv file

My suggestion would be something like this (without using defaultdict):

Copya_file = "path/to/a.csv"
b_file = "path/to/b.csv"

# read from file a.csv
with open(a_file) as f:
    # skip headers
    f.next()
    # get first colum as keys
    keys = (line.split(',')[0] for line in f) 

# create empty dictionary:
d = {}

# read from file b.csv
with open(b_file) as f:
    # gather headers except first key header
    headers = f.next().split(',')[1:]
    # iterate lines
    for line in f:
        # gather the colums
        cols = line.strip().split(',')
        # check to make sure this key should be mapped.
        if cols[0] not in keys:
            continue
        # add key to dict
        d[cols[0]] = dict(
            # inner keys are the header names, values are columns
            (headers[idx], v) for idx, v in enumerate(cols[1:]))

Please note though, that for parsing csv files there is a csv module.

2 of 10
70

UPDATE: For an arbitrary length of a nested dictionary, go to this answer.

Use the defaultdict function from the collections.

High performance: "if key not in dict" is very expensive when the data set is large.

Low maintenance: make the code more readable and can be easily extended.

Copyfrom collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val
🌐
Towards Data Science
towardsdatascience.com › home › latest › nested dictionary python – a complete guide to python nested dictionaries
Nested Dictionary Python - A Complete Guide to Python Nested Dictionaries | Towards Data Science
January 22, 2025 - It means you don’t have to use any specific functions or libraries to create a dictionary. Simply assign it to a variable name, and format the entire thing as JSON. Here’s an example – the following code snippet creates a nested dictionary ...
🌐
Medium
medium.com › @ryan_forrester_ › python-nested-dictionaries-complete-guide-8a61b88a2e02
Python Nested Dictionaries: Complete Guide | by ryan | Medium
October 24, 2024 - A nested dictionary is simply a dictionary that contains other dictionaries as values. Here’s a basic example: employee = { 'name': 'Sarah Chen', 'position': { 'title': 'Senior Developer', 'department': 'Engineering', 'details': { 'level': 'L5', 'team': 'Backend', 'skills': ['Python', 'Go', 'SQL'] } } } Let’s look at different ways to work with nested data:
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to create nested dictionary in python
How to Create Nested Dictionary in Python - Spark By {Examples}
May 31, 2024 - You can create an empty nested dictionary by initializing an empty dictionary as the value for a key in another dictionary. This creates a dictionary with an outer key 'outer_key' whose value is an empty dictionary {}. Can I convert a nested ...
🌐
Programiz
programiz.com › python-programming › nested-dictionary
Python Nested Dictionary (With Examples)
In the above program, we assign a dictionary literal to people[4]. The literal have keys name, age and sex with respective values. Then we print the people[4], to see that the dictionary 4 is added in nested dictionary people. In Python, we use “ del “ statement to delete elements from nested dictionary.
Find elsewhere
🌐
Learn By Example
learnbyexample.org › python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - You can also create a nested dictionary using the dict() constructor. Simply provide the key-value pairs as keyword arguments to dict() function.
🌐
GeeksforGeeks
geeksforgeeks.org › python › define-a-nested-dictionary-in-python
Define a Nested Dictionary in Python - GeeksforGeeks
July 23, 2025 - Below, are the methods for How to Define a Nested Dictionary in Python. ... The most straightforward way to create a nested dictionary is by using curly braces {}. You can nest dictionaries by placing one set of curly braces inside another.
🌐
Medium
medium.com › data-science › nested-dictionary-python-a-complete-guide-to-python-nested-dictionaries-756a7822cb4f
Nested Dictionary Python — A Complete Guide to Python Nested Dictionaries | by Dario Radečić | TDS Archive | Medium
April 19, 2023 - Today you’ll learn what is a nested dictionary, why to use nested dictionaries in Python, how to loop through a nested dictionary in Python, and much more. Regarding library imports, stick this to the top of your script or notebook: ... It will take care of formatting when printing nested dictionaries, so they’re a bit easier to read. There are many ways to create a nested dictionary, but you’ll primarily use two if…
🌐
TutorialsPoint
tutorialspoint.com › creating-a-nested-dictionary-using-a-given-list-in-python
Python - Nested Dictionaries
You can add, remove, or update key-value pairs at any level of the nested structure. We can create a nested dictionary in Python by defining a dictionary where the values of certain keys are themselves dictionaries.
🌐
datagy
datagy.io › home › python posts › python dictionaries › python nested dictionary: complete guide
Python Nested Dictionary: Complete Guide • datagy
December 15, 2022 - An interesting thing about Python dictionaries is that we can even use other dictionaries as their values. This brings us to the main topic of this article. Say we wanted to have a dictionary that contained the user information based on someone’s user ID. Let’s create a dictionary that stores the information on multiple users, broken out by an ID: # Understanding Nested Dictionaries users = { 1: { 'Name': 'Nik', 'Profession':'datagy' }, 2: { 'Name': 'Kate', 'Profession': 'Government' } }
🌐
GeeksforGeeks
geeksforgeeks.org › python-create-nested-dictionary-using-given-list
Create Nested Dictionary using given List – Python | GeeksforGeeks
February 4, 2025 - While this method uses zip() to pair the list and dictionary items, it applies the dict() constructor to explicitly create the final nested dictionary. In this case, the dict() constructor is used with a lambda function to wrap each value in another dictionary.
🌐
Career Karma
careerkarma.com › blog › python › python nested dictionary: a how-to guide
Python Nested Dictionary: A How-To Guide | Career Karma
December 1, 2023 - Our dictionary is stored in the Python variable “ice_cream_flavors”. We added a key called discount to the dictionary. The index position of this key is 0. We set the value of this key to True. Then, we printed out the dictionary with the index value 0 in our ice_cream_flavors nested dictionary.
🌐
AskPython
askpython.com › home › how to create a nested dictionary via for loop?
How to Create a Nested Dictionary via for Loop? - AskPython
March 25, 2023 - Creating a nested dictionary using a for loop might sound like a new concept but it is an easier and much more systematic approach to create a nested dictionary using a for loop which can then be used to loop through the nested data structure. After a dictionary is created using a for loop, another for loop may be used to iterate through the dictionary and access elements of the dictionary. If you want to know more about dictionaries in python, you might want to check this out.
🌐
LabEx
labex.io › tutorials › python-how-to-create-a-nested-dictionary-in-python-397732
How to create a nested dictionary in Python | LabEx
Learn how to create and manipulate nested dictionaries in Python, a powerful data structure for organizing complex information. Discover techniques for accessing and modifying nested dictionaries efficiently.