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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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, 'geeks' : 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)) 

chevron_right


Output :

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

 



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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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, 'geeks' : 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)) 

chevron_right


Output :

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.