Open In App

Python – Swapping Hierarchy in Nested Dictionaries

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.
 

Python3




# Python3 code to demonstrate working of
# Swapping Hierarchy in Nested Dictionaries
# Using loop + items()
 
# initializing dictionary
test_dict = {'Gfg': { 'a' : [1, 3], 'b' : [3, 6], 'c' : [6, 7, 8]},
             'Best': { 'a' : [7, 9], 'b' : [5, 3, 2], 'd' : [0, 1, 0]}}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Swapping Hierarchy in Nested Dictionaries
# Using loop + items()
res = dict()
for key, val in test_dict.items():
    for key_in, val_in in val.items():
        if key_in not in res:
            temp = dict()
        else:
            temp = res[key_in]
        temp[key] = val_in
        res[key_in] = temp
 
# printing result
print("The rearranged dictionary : " + str(res))


Output : 
The original dictionary : {‘Gfg’: {‘a’: [1, 3], ‘c’: [6, 7, 8], ‘b’: [3, 6]}, ‘Best’: {‘d’: [0, 1, 0], ‘a’: [7, 9], ‘b’: [5, 3, 2]}} 
The rearranged dictionary : {‘d’: {‘Best’: [0, 1, 0]}, ‘a’: {‘Gfg’: [1, 3], ‘Best’: [7, 9]}, ‘c’: {‘Gfg’: [6, 7, 8]}, ‘b’: {‘Gfg’: [3, 6], ‘Best’: [5, 3, 2]}} 
 

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.
 

Python3




# Python3 code to demonstrate working of
# Swapping Hierarchy in Nested Dictionaries
# Using  defaultdict() + loop
from collections import defaultdict
 
# initializing dictionary
test_dict = {'Gfg': { 'a' : [1, 3], 'b' : [3, 6], 'c' : [6, 7, 8]},
             'Best': { 'a' : [7, 9], 'b' : [5, 3, 2], 'd' : [0, 1, 0]}}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Swapping Hierarchy in Nested Dictionaries
# Using  defaultdict() + loop
res = defaultdict(dict)
for key, val in test_dict.items():
    for key_in, val_in in val.items():
        res[key_in][key] = val_in
 
# printing result
print("The rearranged dictionary : " + str(dict(res)))


Output : 
The original dictionary : {‘Gfg’: {‘a’: [1, 3], ‘c’: [6, 7, 8], ‘b’: [3, 6]}, ‘Best’: {‘d’: [0, 1, 0], ‘a’: [7, 9], ‘b’: [5, 3, 2]}} 
The rearranged dictionary : {‘d’: {‘Best’: [0, 1, 0]}, ‘a’: {‘Gfg’: [1, 3], ‘Best’: [7, 9]}, ‘c’: {‘Gfg’: [6, 7, 8]}, ‘b’: {‘Gfg’: [3, 6], ‘Best’: [5, 3, 2]}} 
 

Using zip and dict:

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.

Python3




def swap_hierarchy(test_dict):
    new_dict = {key2: {key1: test_dict[key1][key2] for key1 in test_dict} for key2 in test_dict[next(iter(test_dict))]}
    return new_dict
test_dict1 = {'Gfg': {'a': [1, 3, 7, 8], 'b': [4, 9], 'c': [0, 7]}}
output1 = swap_hierarchy(test_dict1)
print(output1) # {'a': {'Gfg': [1, 3, 7, 8]}, 'b': {'Gfg': [4, 9]}, 'c': {'Gfg': [0, 7]}}
 
test_dict2 = {'Gfg': {'best': [1, 3, 4]}}
output2 = swap_hierarchy(test_dict2)
print(output2) # {'best': {'Gfg': [1, 3, 4]}}


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)



Similar Reads

Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Convert a List of Dictionaries into a Set of Dictionaries
Python's versatility allows developers to manipulate data in various ways. When working with a list of dictionaries, there might be scenarios where you want to convert it into a set of dictionaries to eliminate duplicates or for other reasons. In this article, we'll explore three different methods to achieve this goal with code examples. Convert A
3 min read
Python | Remove duplicate dictionaries from nested dictionary
Given a nested dictionary, the task is to remove duplicate dictionaries from the dictionary. Given below are few methods to complete the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # for removing duplicate values from dictionary # initialising dictionary ini_dict = {'a':{'b':1, 'c':2}, 'b':{'b':1, 'c':2}, 'c':{
6 min read
Python - Removing Nested None Dictionaries
Sometimes, while working with Records, we can have a problem in which we need to perform the removal of nested records from the dictionary which are empty. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed. Method #1 : Using dict() + filter() This is one of the way in which this task can
4 min read
Python - Convert Flat dictionaries to Nested dictionary
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. Conv
4 min read
Accessing Value Inside Python Nested Dictionaries
We are given a nested dictionary and our task is to access the value inside the nested dictionaries in Python using different approaches. In this article, we will see how we can access value inside the nested dictionaries in Python. Example: Input: market = {"fruits": {"apple": 10, "orange": 40, "strawberry": 30, "grapes": 200}, "vegetables": {"car
3 min read
Python - Convert String to Nested Dictionaries
Sometimes, while working with dictionaries, we can have a problem in which we need to convert a String to nested dictionary, each separator occurrence meaning a new nesting. This is a particular problem but can occur in data domains and day-day programming. Let's discuss certain way in which this task can be done. Method : Using loop + recursion Th
2 min read
Python Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15->12->13->20->14, x = 12, y = 20 Output:
5 min read