Python - Convert Flat dictionaries to Nested dictionary
Last Updated :
05 Dec, 2023
Sometimes, while working with records, we can have a problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have applications in many domains in which data is used extensively. Let's discuss certain ways by which we can convert flat dictionaries into nested dictionaries.
Convert Flat Dictionaries to Nested dictionary in Python
Below are the ways by which we can convert flat dictionaries to nested dictionary in Python:
- Using dict() + key access
- Using zip
- Using a for loop and dictionary comprehension
- Using defaultdict() and reduce()
Convert Flattened Dictionaries to Nested dictionary 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
# 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))
Output:
The original dictionary 1 is : {'gfg': 1, 'best': 2}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The nested dictionary is : {'level1': {'gfg': 1, 'best': 2}, 'level2': {'for': 3, 'geeks': 5}}
Time complexity: O(1)
Auxiliary Space: O(1)
Python Convert Flat Dictionaries to Nested dictionary 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
# 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))
Output:
The original dictionary 1 is : {'gfg': 1, 'best': 2}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The nested dictionary is : {'level1': {'gfg': 1, 'best': 2}, 'level2': {'for': 3, 'geeks': 5}}
Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary Space: O(1), constant extra space is required
Convert Flat Dictionaries to Nested dictionary Using a for loop and dictionary comprehension
In this example, flat dictionaries test_dict1
and test_dict2
are transformed into a nested dictionary res
using a for loop and dictionary comprehension, associating each original dictionary with its corresponding key in the list key_dict
.
Python3
# 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 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, 'geeks': 5}
The nested dictionary is : {'level1': {'gfg': 1, 'best': 2}, 'level2': {'for': 3, 'geeks': 5}}
Time Complexity: O(n), where n is the number of items in the dictionaries.
Auxiliary Space: O(n)
Python Convert Flat Dictionaries to Nested dictionary Using defaultdict() and reduce() Functions
In this example, flat dictionaries test_dict1
and test_dict2
are transformed into a nested dictionary (nested_dict
) using defaultdict
, functools.reduce
, and operator.setitem
to iteratively update the nested structure with key-value pairs.
Python3
from collections import defaultdict
from functools import reduce
import operator
# 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 defaultdict, functools, operators
nested_dict = defaultdict(dict)
# Combine key-value pairs into a single list
key_value_pairs = [('level1', test_dict1), ('level2', test_dict2)]
# Use functools.reduce and operator.setitem to create the nested dictionary
reduce(lambda d, kv: operator.setitem(
d, kv[0], kv[1]) or d, key_value_pairs, nested_dict)
# Convert defaultdict to regular dictionary
nested_dict = dict(nested_dict)
# printing result
print("The nested dictionary is : " + str(nested_dict))
Output:
The original dictionary 1 is : {'gfg': 1, 'best': 2}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The nested dictionary is : {'level1': {'gfg': 1, 'best': 2}, 'level2': {'for': 3, 'geeks': 5}}
Similar Reads
Python - Convert Dictionaries List to Order Key Nested dictionaries Given list of dictionaries, our task is to convert a list of dictionaries into a dictionary where each key corresponds to the index of the dictionary in the list and the value is the dictionary itself. For example: consider this list of dictionaries: li = [{"Gfg": 3, 4: 9}, {"is": 8, "Good": 2}] the
3 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
8 min read
Python - Convert Nested Dictionary into Flattened Dictionary We are given a nested dictionary we need to flatten the dictionary into single dictionary. For example, we are given a nested dictionary a = {'a': 1, 'b': {'x': 2, 'y': {'z': 3}}, 'c': {'m': 4} } we need to flatten the dictionary so that output becomes {'a': 1, 'c_m': 4, 'b_x': 2, 'b_y_z': 3}. We ca
2 min read
Convert List of Dictionaries to Dictionary of Lists - Python We are given a list of dictionaries we need to convert it to dictionaries of lists. For example, we are given a list of dictionaries li = [{'manoj': 'java', 'bobby': 'python'}, {'manoj': 'php', 'bobby': 'java'}, {'manoj': 'cloud', 'bobby': 'big-data'}] we need to convert this to dictionary of list s
3 min read
Convert Nested Dictionary to List in Python In this article, weâll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list.Pythona = { "a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}, } # Convert nested dictionary to a list of li
3 min read