Open In App

Python – Create Nested Dictionary using given List

Last Updated : 14 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list and dictionary, map each element of list with each item of dictionary, forming nested dictionary as value.

Input : test_dict = {‘Gfg’ : 4, ‘best’ : 9}, test_list = [8, 2] Output : {8: {‘Gfg’: 4}, 2: {‘best’: 9}} Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4} and so on. Input : test_dict = {‘Gfg’ : 4}, test_list = [8] Output : {8: {‘Gfg’: 4}} Explanation : Index-wise key-value pairing from list [8] to dict {‘Gfg’ : 4}.

Method #1 : Using loop + zip() 

This is one of the ways in which this task can be performed. In this, we combine both the lists using zip() and loop is used to do iteration of zipped keys and dictionary construction.

Python3




# Python3 code to demonstrate working of
# Nested Dictionary with List
# Using loop + zip()
 
# initializing dictionary and list
test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}
test_list = [8, 3, 2]
 
# printing original dictionary and list
print("The original dictionary is : " + str(test_dict))
print("The original list is : " + str(test_list))
 
# using zip() and loop to perform
# combining and assignment respectively.
res = {}
for key, ele in zip(test_list, test_dict.items()):
    res[key] = dict([ele])
         
# printing result
print("The mapped dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}
The original list is : [8, 3, 2]
The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}

Time complexity: O(n*n), where n is the length of the test_list. The zip() + loop takes O(n*n) time
Auxiliary Space: O(n), extra space of size n is required

Method #2 : Using dictionary comprehension + zip()

This is yet another way in which this task can be performed. In this, we perform similar task as above method, but in one liner using dictionary comprehension

Python3




# Python3 code to demonstrate working of
# Nested Dictionary with List
# Using dictionary comprehension + zip()
 
# initializing dictionary and list
test_dict = {'Gfg' : 4, 'is' : 5, 'best' : 9}
test_list = [8, 3, 2]
 
# printing original dictionary and list
print("The original dictionary is : " + str(test_dict))
print("The original list is : " + str(test_list))
 
# zip() and dictionary comprehension mapped in one liner to solve
res = {idx: {key : test_dict[key]} for idx, key in zip(test_list, test_dict)}
         
# printing result
print("The mapped dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 4, 'is': 5, 'best': 9}
The original list is : [8, 3, 2]
The mapped dictionary : {8: {'Gfg': 4}, 3: {'is': 5}, 2: {'best': 9}}


Similar Reads

Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Create a Nested Dictionary from Text File Using Python
We are given a text file and our task is to create a nested dictionary using Python. In this article, we will see how we can create a nested dictionary from a text file in Python using different approaches. Create a Nested Dictionary from Text File Using PythonBelow are the ways to Create Nested Dictionary From Text File using Python: Using json.lo
3 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Inner Nested Value List Mean in Dictionary
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract the mean of nested value lists in dictionary. This problem can have application in many domains including web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using mean() + loop The
5 min read
Python - Unnest single Key Nested Dictionary List
Sometimes, while working with Python data, we can have a problem in which we need to perform unnesting of all the dictionaries which have single nesting of keys, i.e a single key and value and can easily be pointed to outer key directly. This kind of problem is common in domains requiring data optimization. Let's discuss certain ways in which this
7 min read
Python - K list Nested Dictionary Mesh
Given 2 lists, create nested mesh with constant List. Input : test_list1 = [4, 6], test_list2 = [2, 7], K = [] Output : {4: {2: [], 7: []}, 6: {2: [], 7: []}} Explanation : Nested dictionary initialized with []. Input : test_list1 = [4], test_list2 = [2], K = [1] Output : {4: {2: [1]}} Explanation : Nested dictionary initialized with [1]. Method :
2 min read
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictionary into Pandas DataframeBelow are the methods th
4 min read