![]() |
VOOZH | about |
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform hierarchy swapping of nested dictionaries. This problem can have application in domains which require dictionary restructuring. Let's discuss certain ways in which this task can be performed.
Input : test_dict = {'Gfg': { 'a' : [1, 3, 7, 8], 'b' : [4, 9], 'c' : [0, 7]}}
Output : {'c': {'Gfg': [0, 7]}, 'b': {'Gfg': [4, 9]}, 'a': {'Gfg': [1, 3, 7, 8]}}
Input : test_dict = {'Gfg': {'best' : [1, 3, 4]}}
Output : {'best': {'Gfg': [1, 3, 4]}}
Method #1 : Using loop + items()
The combination of above functions can be used to solve this problem. In this, we iterate the dictionary and restructure using brute force. The items() is used to extract all the key-value pairs of dictionary.
Time Complexity: O(n*n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using defaultdict() + loop
This is yet another brute force way to solve this problem. In this, we reduce a key test step by using defaultdict() rather than conventional dictionary.
Approach:
Define a function swap_hierarchy() that takes a dictionary as input.
Initialize a new empty dictionary new_dict.
For each key2 in the nested dictionary accessed by test_dict[next(iter(test_dict))]:
a. Create a new key in new_dict with value key2.
b. Assign to the value of the new key a dictionary comprehension that swaps the keys and values of test_dict such that the value of each new key is the value of the original key2 in the nested dictionary of the corresponding original key1 in test_dict.
Return the new_dict.
Test the function with example inputs and print the output.
{'a': {'Gfg': [1, 3, 7, 8]}, 'b': {'Gfg': [4, 9]}, 'c': {'Gfg': [0, 7]}}
{'best': {'Gfg': [1, 3, 4]}}Time Complexity: O(n)
Auxiliary Space: O(n)