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
🌐
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 Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
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 ...
Discussions

How do you create nested dict in Python? - Stack Overflow
I have 2 CSV files: 'Data' and 'Mapping': 'Mapping' file has 4 columns: Device_Name, GDN, Device_Type, and Device_OS. All four columns are populated. 'Data' file has these same columns, with Device... More on stackoverflow.com
🌐 stackoverflow.com
Readability for defining a nested dict

Literals should generally be preferred over calling the constructors, so in my opinion

d = {key: {'k1': '', 'k2': []} for key in all_keys}

would be the better of the two.

Another potential option would be:

all_keys = [...]
data = dict.fromkeys(all_keys, {'k1': '', 'k2': []})

but I don't remember if this would cause problems with mutable types - it's possible every inner dict or the lists would actually be the exact same.

More on reddit.com
🌐 r/learnpython
5
1
November 3, 2023
Using get() with nested dictionary.
When get misses, the default return is None, which can't itself be "get"ed. You could have get give a different miss, like a dictionary, which could then give you further misses. I might do that for a single layer, but with a bunch, I would probably do something like create a function to do the search for me, probably recursively. edit: some great ideas here: https://stackoverflow.com/questions/25833613/safe-method-to-get-value-of-nested-dictionary Having never had the chance to use reduce, I would 100% use one of those solutions. More on reddit.com
🌐 r/learnpython
9
5
April 10, 2024
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 › python-nested-dictionary
Python Nested Dictionary - GeeksforGeeks
July 12, 2025 - Creating a Nested Dictionary means placing dictionaries as values inside an outer dictionary using curly braces {}. ... This example creates a nested dictionary to store details of multiple students.
🌐
Learn By Example
learnbyexample.org › python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - In this example, the deep_update function iterates through the keys and values of the second dictionary. If a value is itself a dictionary (a collections.abc.Mapping), the function recursively calls itself to merge the nested dictionaries. Otherwise, it simply updates the value in the source 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 …
🌐
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 - Here’s an example – the following code snippet creates a nested dictionary of employees, where employee email is set for the dictionary key, and additional information as a dictionary value.
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 10-5-nested-dictionaries-and-dictionary-comprehension
10.5 Nested dictionaries and dictionary comprehension - Introduction to Python Programming | OpenStax
March 13, 2024 - You want to create a nested dictionary ... in each department. Write a Python program that when given a dictionary, employees, outputs a nested dictionary, dept_employees, which groups employees by department....
Find elsewhere
🌐
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 - He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tuto... read more about the author ... You forgot to include the “.items():” in line 11 on the last example of iterating through a nested dictionary.
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
🌐
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 - Nested dictionary in Python is a dictionary within another dictionary. This means that the values of the outer dictionary are themselves dictionaries. 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.
🌐
CodeGym
codegym.cc › java blog › learning python › python nested dictionary
Python Nested Dictionary
November 12, 2024 - from collections import defaultdict from copy import deepcopy # Using defaultdict for nested dictionaries company = defaultdict(lambda: defaultdict(dict)) # Deep copy example new_company = deepcopy(company)
🌐
SitePoint
sitepoint.com › python hub › nested dictionaries
Python - Nested Dictionaries | SitePoint — SitePoint
The final example shows how to create even more complex nested structures by adding tourist attractions. For each country, we're creating a detailed catalog of places to visit, complete with additional information about each location. You can add elements at any level using standard dictionary assignments:
🌐
Tutorialspoint
tutorialspoint.com › python › python_nested_dictionaries.htm
Python - Nested Dictionaries
In the following example, we are defining a nested dictionary "students" where each key represents a student's name and its value is another dictionary containing details about the student.
🌐
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.
🌐
datagy
datagy.io › home › python posts › python dictionaries › python nested dictionary: complete guide
Python Nested Dictionary: Complete Guide • datagy
December 15, 2022 - 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' } }
🌐
iO Flood
ioflood.com › blog › python-nested-dictionary
Python Nested Dictionary Guide (With Examples)
January 30, 2024 - In this example, we’ve created a nested dictionary my_dict with two keys: ‘John’ and ‘Jane’. Each key has its own dictionary as a value, containing further key-value pairs. We then access the ‘Age’ of ‘John’ by chaining the keys, resulting in the output ’30’. This is just a basic way to create and use a nested dictionary in Python.
🌐
Scaler
scaler.com › home › topics › what is nested dictionary in python?
What is Nested Dictionary in Python? | Scaler Topics
May 4, 2023 - The fromkeys() method in python dictionary creates a new dictionary with the default value for all specified keys. In case we do not specify any default value then, all the keys are set to None. ... We can use the dict.fromkeys() method to create a nested dictionary with some default values. For example, consider the given code below --
🌐
Codingem
codingem.com › home › python how to access nested dictionary (with 5+ examples)
Python How to Access Nested Dictionary (with 5+ Examples)
December 4, 2022 - To access a nested dictionary values, apply the access operator on the dictionary twice. For example dict['key1']['key2'].
🌐
GeeksforGeeks
geeksforgeeks.org › python › define-a-nested-dictionary-in-python
Define a Nested Dictionary in Python - GeeksforGeeks
July 23, 2025 - ... The most straightforward way ... another. In this example, the outer dictionary has a key 'outer_key' with a corresponding value that is another dictionary with keys 'inner_key1' and 'inner_key2'....
🌐
GeeksforGeeks
geeksforgeeks.org › python › define-a-3-level-nested-dictionary-in-python
Define a 3 Level Nested Dictionary in Python - GeeksforGeeks
July 23, 2025 - # Using recursion def add_nested_key(dictionary, keys, value): if len(keys) == 1: dictionary[keys[0]] = value else: add_nested_key(dictionary.setdefault(keys[0], {}), keys[1:], value) nested_dict = {} add_nested_key(nested_dict, ['first_level_key1', 'second_level_key1', 'third_level_key1'], 'value1') # Example print(nested_dict['first_level_key1']['second_level_key1']['third_level_key1']) ... In this article we studied about creating a 3-level nested dictionary in Python using various methods.