You can use defaultdict here. multi need not be sorted.

from collections import defaultdict
out=defaultdict(dict)
for v,k,vs in multi:
    out[k]={**out[k],**{v:vs[0]}}

Output

defaultdict(dict,
            {77766: {14: 2, 15: 1},
             88866: {70: 1, 71: 2, 72: 5, 73: 4, 74: 3},
             99966: {79: 1, 80: 2}})

EDIT:

Sorting the inner dictionaries.

out={k:dict(sorted(v.items(),key=lambda x:x[1])) for k,v in out.items()}

Output:

{77766: {15: 1, 14: 2},
 88866: {70: 1, 71: 2, 74: 3, 73: 4, 72: 5},
 99966: {79: 1, 80: 2}}
Answer from Ch3steR on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_dictionaries_nested.asp
Python - Nested Dictionaries
Remove List Duplicates Reverse a String Add Two Numbers · 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:
🌐
Learn By Example
learnbyexample.org › python-nested-dictionary
Python Nested Dictionary - Learn By Example
June 20, 2024 - Learn to create a Nested Dictionary in Python, access change add and remove nested dictionary items, iterate through a nested dictionary and more.
🌐
Programiz
programiz.com › python-programming › nested-dictionary
Python Nested Dictionary (With Examples)
It's a collection of dictionaries into one single dictionary. nested_dict = { 'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}} Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two dictionary each having own key and value.
🌐
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 {}.
🌐
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 - Dictionary merging just means you want to take two or more dictionaries and combine them into a single one. It helps if the structure of dictionaries is identical, but it’s not required, since this is Python. To demonstrate, let’s declare a new nested dictionary of employees:
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
🌐
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.
Find elsewhere
🌐
Medium
medium.com › @ryan_forrester_ › python-nested-dictionaries-complete-guide-8a61b88a2e02
Python Nested Dictionaries: Complete Guide | by ryan | Medium
October 24, 2024 - When working with nested dictionaries, using `get()` helps avoid KeyError exceptions: def get_nested_value(dict_obj, keys, default=None): """Safely get nested dictionary values.""" current = dict_obj for key in keys: if isinstance(current, dict): current = current.get(key, default) else: return default return current # Usage employee = { 'name': 'Sarah Chen', 'position': { 'title': 'Senior Developer' } } # Safe access with multiple keys print(get_nested_value(employee, ['position', 'title'])) # Output: Senior Developer print(get_nested_value(employee, ['position', 'salary'], 'Not specified')) # Output: Not specified
🌐
Stack Overflow
stackoverflow.com › questions › 65223196 › creating-a-nested-dictionary-from-2-dictionaries
python - Creating a Nested Dictionary from 2 Dictionaries - Stack Overflow
I have searched for days now try to find something similar to this but the examples I see aren't quite doing what I am looking for and/or are not working for me and I don't know what I may be missing or if something is wrong with my dictionaries. Can I get some advice? ... pro_go: { Q9Y7X7 : ['GO:0003674','GO:0005829'...], 'Q9Y819': ['GO:0008150','GO:0005794',...]... } go_def: { 'GO:0010332': 'response to gamma radiation', 'GO:0010337': 'cellulose synthase', ... } ... pro_go_def: { Q9Y7X7: { 'GO:xxxxxx': response, 'GO:xxxxxx': metabolism... }, Q9Y819:{ 'GO:xxxxx': cell wall, 'GO:xxxxx': 'transporter activity', } .... } So I need a dictionary pro_go key , pro_go value=go_def key, go_def value
🌐
YouTube
youtube.com › watch
How to Create a Nested Dictionary in Python | Amit Thinks - YouTube
In this video, learn how to Create a Nested Dictionary in Python. Dictionary represents the key-value pair in Python, enclosed in curly braces. Keys are uniq...
Published   September 9, 2022
🌐
Stack Overflow
stackoverflow.com › questions › 75746732 › how-to-create-a-nested-dictionary-by-checking-two-other-dictionaries-keys-and-va
How to create a nested dictionary by checking two other dictionaries keys and values in python - Stack Overflow
I have two dictionaries as dict2={'A': {'A': 'kept', 'B': 'kept', 'H': 'kept', 'G': 'kept'}} dict1={'A': ['B', 'C', 'D', 'E'], 'B': ['E'], 'C': ['F', 'D'], 'D': ['G'], 'E': ['H', 'G'], '...
🌐
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 - One of the most straightforward methods for creating a nested dictionary in Python is using the curly braces {} notation. It allows you to specify the keys and values of the dictionary using a simple syntax.
🌐
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 ...
🌐
TutorialsPoint
tutorialspoint.com › How-to-create-nested-Python-dictionary
How to create nested Python dictionary?
November 8, 2022 - We can iterate through a nested dictionary by using nested loops. The outer loop iterates over the keys and values of the main dictionary, while the inner loop iterates over the keys and values of the nested dictionaries.
🌐
TutorialsPoint
tutorialspoint.com › creating-a-nested-dictionary-using-a-given-list-in-python
Creating a Nested Dictionary using a given List in Python
:")) for i in range(num_employees): employee_id = int(input(f"Enter Employee {i+1} ID: ")) name = input(f"Enter Employee {i+1} Name: ") age = int(input(f"Employee {i+1} Age: ")) department = input(f"Employee {i+1} Department: ") if department in nested_dict: nested_dict[department][employee_id] = {'name': name, 'age': age} else: nested_dict[department] = {employee_id: {'name': name, 'age': age}} print("Nested Dictionary:", nested_dict) from collections import defaultdict employee_list = [ (101, 'John', 30, 'HR'), (102, 'Jane', 28, 'Engineering'), (103, 'Mike', 32, 'Finance'), (104, 'Alice', 25, 'Engineering'), ] employee_data = defaultdict(dict) for employee in employee_list: employee_id, name, age, department = employee employee_data[department][employee_id] = {'name': name, 'age': age} print("Nested Dictionary using defaultdict:", dict(employee_data))
🌐
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' } }
🌐
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 - In the above example, the key is ... dictionaries. To merge nested dictionaries, python offers a built-in update() method to merge the keys and values of one nested dictionary into another....
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai