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

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

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

d = {}  # 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):

a_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 9
428

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

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

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

d = {}  # 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):

a_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 9
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.

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-nested-dictionary
Python Nested Dictionary - GeeksforGeeks
1 month ago - A nested dictionary can be created by storing one or more dictionaries as values inside another dictionary.
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
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
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
Creating a nested dictionary

The values in day_dict are immutable, so you can't affect what's contained in 'item', I would re-write the loop as:

for date in day_dict.keys():
day_dict[date] = {}
for team in teams:
day_dict[date][team] = None

Or you can make day_dict[date][team] = {}, whatevaa you want

More on reddit.com
🌐 r/learnpython
5
5
September 2, 2020
🌐
W3Schools
w3schools.com › python › python_dictionaries_nested.asp
Python - Nested Dictionaries
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... A dictionary can contain dictionaries, this is called nested dictionaries. Create a dictionary that contain three dictionaries:
🌐
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.
🌐
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 …
🌐
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.
Find elsewhere
🌐
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.
🌐
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 - How to create a nested dictionary in Python? Creating a nested dictionary in Python involves defining a dictionary where the values are themselves
🌐
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.
🌐
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 › 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.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
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 this rather than hand roll the nesting logic.
🌐
AskPython
askpython.com › python › dictionary › create-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.
🌐
iO Flood
ioflood.com › blog › python-nested-dictionary
Python Nested Dictionary Guide (With Examples)
January 30, 2024 - Think of a nested dictionary in Python as a family tree, where each branch can have its own smaller branches. It’s a powerful tool for handling complex data structures, providing a versatile and handy tool for various tasks. This guide will walk you through the creation, manipulation, and ...
🌐
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.
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python › nested dictionary in python: create, access, update, and loop
Python Nested Dictionary: Create, Access, Update, Delete, and Iterate
June 19, 2026 - Create them with literals, dict, or zip of parallel lists; read and update with chained indices or safer .get; delete with del or pop at the right level; iterate with nested for loops over items().