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
Top answer
1 of 10
426

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
🌐
W3Schools
w3schools.com › python › python_dictionaries_nested.asp
Python - Nested Dictionaries
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... A dictionary can contain dictionaries, this is called nested dictionaries. Create a dictionary that contain three dictionaries:
Discussions

Getting lost trying to create a nested dictionary
I’ve been trying to do this for 3 days now. I have watched YouTubes, looked up nested dictionaries on about a dozen different sites (e.g. https://discuss.python.org/t/how-to-create-a-dictionary-from-scanning-text/9676/2 but I still can’t do what must be a simple thing. More on discuss.python.org
🌐 discuss.python.org
15
0
August 26, 2021
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
Introduce nested creation of dictionary keys - Ideas - Discussions on Python.org
I recently came across a use case where I needed to created nested keys, basically it was where I needed convert a web form like datastructure with keys like this “customer[profile][name]” into a deeply nested JSON structure. In the end it was easier to pull in a specific library to handle ... More on discuss.python.org
🌐 discuss.python.org
0
January 13, 2025
Multiple dictionaries versus nested dictionary?
Personally I'd use a list of tuples for that. data = [('Ben',21), ('Jerry', 22)] Or perhaps namedtuples or dataclasses. But if you like the dictionaries that's fine too. There's no best here, it's just whatever you find is the easiest to work with. More on reddit.com
🌐 r/learnpython
8
2
June 7, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › define-a-nested-dictionary-in-python
Define a Nested Dictionary in Python - GeeksforGeeks
July 23, 2025 - This method provides a more explicit way to define nested dictionaries by calling the dict() constructor for the outer dictionary and providing key-value pairs for the inner dictionaries. ... The defaultdict class from the collections module can be employed to create a nested dictionary with default values for missing keys.
🌐
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'} }
🌐
Learn By Example
learnbyexample.org › python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - The most straightforward way to create a nested dictionary is to specify dictionaries as the values for the keys within curly braces.
🌐
Programiz
programiz.com › python-programming › nested-dictionary
Python Nested Dictionary (With Examples)
Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two dictionary each having own key and value. We're going to create dictionary of people within a dictionary.
🌐
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 - This allows you to create a hierarchical structure, providing a way to organize and manage data more efficiently. ... You can create an empty nested dictionary by initializing an empty dictionary as the value for a key in another dictionary.
Find elsewhere
🌐
Quora
quora.com › How-do-you-create-a-nested-dictionary-through-normal-iterating-Python-Python-3-x-development
How to create a nested dictionary through normal iterating (Python, Python 3.x, development) - Quora
One could use the zip() function along with two lists objects, however the dictionary’s in Python have their own highly advanced Caching and Hash Tables designed specifically for them. But if you were to do it any different than how they are set up would be futile without having the following→ ... In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:
🌐
Python.org
discuss.python.org › python help
Getting lost trying to create a nested dictionary - Python Help - Discussions on Python.org
August 26, 2021 - I’ve been trying to do this for 3 days now. I have watched YouTubes, looked up nested dictionaries on about a dozen different sites (e.g. https://discuss.python.org/t/how-to-create-a-dictionary-from-scanning-text/9676/2 …
🌐
Tutorialspoint
tutorialspoint.com › python › python_nested_dictionaries.htm
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.
🌐
Medium
medium.com › @ryan_forrester_ › python-nested-dictionaries-complete-guide-8a61b88a2e02
Python Nested Dictionaries: Complete Guide | by ryan | Medium
October 24, 2024 - Python Nested Dictionaries: Complete Guide Nested dictionaries are essential when you need to organize complex, hierarchical data in Python. They’re particularly useful for working with JSON data …
🌐
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.
🌐
Python.org
discuss.python.org › ideas
Introduce nested creation of dictionary keys - Ideas - Discussions on Python.org
January 13, 2025 - I recently came across a use case where I needed to created nested keys, basically it was where I needed convert a web form like datastructure with keys like this “customer[profile][name]” into a deeply nested JSON structure. In the end it was easier to pull in a specific library to handle ...
🌐
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.
🌐
SitePoint
sitepoint.com › python hub › nested dictionaries
Python - Nested Dictionaries | SitePoint — SitePoint
Note: The dictionary union operator (|) creates a new dictionary by merging dict1 and dict2, but it performs a shallow merge. For top-level keys, if a key exists in both dictionaries, the value from dict2 will overwrite the value from dict1. If the value associated with a key is itself a dictionary, this nested dictionary won't be merged; instead, it will be directly overwritten by the value from dict2.
🌐
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.
🌐
CodeGym
codegym.cc › java blog › learning python › python nested dictionary
Python Nested Dictionary
November 12, 2024 - Use defaultdict: From the collections module, this can simplify nested dictionary creation.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › nested dictionary python
Nested Dictionary Python | How to Create a Nested Dictionary Python?
February 10, 2023 - To create a nested dictionary in Python, you must separate dictionaries with commas enclosed within braces.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai