![]() |
VOOZH | about |
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.
Below are the ways by which we can convert flat dictionaries to nested dictionary in Python:
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.
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)
This is another way in which this task can be performed. In this we link inner keys to outer keys using zip().
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
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.
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)
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.
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}}