Friday, November 15, 2024
Google search engine
HomeLanguagesPython – Convert Flat dictionaries to Nested dictionary

Python – Convert Flat dictionaries to Nested dictionary

Sometimes, while working with records, we can have problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have application in many domains in which data is used extensively. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using dict() + key access This is one of the way in which this task can be performed. In this, we construct empty dictionary using dict and assign a new level to dictionary using manual brute key access. 

Python3




# Python3 code to demonstrate working of
# Convert Flat dictionaries to Nested dictionary
# Using key access + dict()
 
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'best' : 2}
test_dict2 = {'for' : 3, 'Lazyroar' : 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Convert Flat dictionaries to Nested dictionary
# Using key access + dict()
res = dict()
res["level1"] = test_dict1
res['level2'] = test_dict2
 
# printing result
print("The nested dictionary is : " + str(res))


Output : 

The original dictionary 1 is : {‘gfg’: 1, ‘best’: 2} The original dictionary 2 is : {‘Lazyroar’: 5, ‘for’: 3} The nested dictionary is : {‘level2’: {‘Lazyroar’: 5, ‘for’: 3}, ‘level1’: {‘gfg’: 1, ‘best’: 2}}

Time complexity: O(1) – constant time complexity, as the input size is fixed and the operations performed on it are not dependent on the input size.
Auxiliary Space: O(1) – constant auxiliary space complexity, as the size of the output dictionary is fixed and the memory used to store it is not dependent on the input size.

Method #2 : Using zip() This is another way in which this task can be performed. In this we link inner keys to outer keys using zip(). 

Python3




# Python3 code to demonstrate working of
# Convert Flat dictionaries to Nested dictionary
# Using zip()
 
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'best' : 2}
test_dict2 = {'for' : 3, 'Lazyroar' : 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Convert Flat dictionaries to Nested dictionary
# Using zip()
key_dict = ['level1', 'level2']
dict_list = [test_dict1, test_dict2]
res = dict(zip(key_dict, dict_list))
 
# printing result
print("The nested dictionary is : " + str(res))


Output : 

The original dictionary 1 is : {‘gfg’: 1, ‘best’: 2} The original dictionary 2 is : {‘Lazyroar’: 5, ‘for’: 3} The nested dictionary is : {‘level2’: {‘Lazyroar’: 5, ‘for’: 3}, ‘level1’: {‘gfg’: 1, ‘best’: 2}}

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary Space: O(1), constant extra space is required

Method #3: Using a for loop and dictionary comprehension

Step-by-step approach:

  • Initialize dictionaries test_dict1 and test_dict2 with key-value pairs.
  • Print the original dictionaries using the print() function.
  • Create a list key_dict containing the key names of the levels we want to create in the nested dictionary.
  • Create a list dict_list containing the original dictionaries we want to convert.
  • Use a for loop and dictionary comprehension to create a nested dictionary by iterating through the key_dict list and using each item as a key name for the current dictionary in the dict_list. The dictionary comprehension creates a new key-value pair in the nested dictionary for each key-value pair in the current dictionary.
    • Assign the nested dictionary to a variable called res.
  • Print the result using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Convert Flat dictionaries to Nested dictionary
# Using a for loop and dictionary comprehension
 
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'best' : 2}
test_dict2 = {'for' : 3, 'Lazyroar' : 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Convert Flat dictionaries to Nested dictionary
# Using a for loop and dictionary comprehension
key_dict = ['level1', 'level2']
dict_list = [test_dict1, test_dict2]
 
res = {}
for key, d in zip(key_dict, dict_list):
    res[key] = {k:v for k,v in d.items()}
 
# printing result
print("The nested dictionary is : " + str(res))


Output

The original dictionary 1 is : {'gfg': 1, 'best': 2}
The original dictionary 2 is : {'for': 3, 'Lazyroar': 5}
The nested dictionary is : {'level1': {'gfg': 1, 'best': 2}, 'level2': {'for': 3, 'Lazyroar': 5}}

Time Complexity: O(n), where n is the number of items in the dictionaries.
Auxiliary Space: O(n), since we are creating a new nested dictionary with the same number of items as the original dictionaries.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments