Python - Inversion in nested dictionary
Last Updated :
27 Mar, 2023
Given a nested dictionary, perform inversion of keys, i.e innermost nested becomes outermost and vice-versa.
Input : test_dict = {"a" : {"b" : {}}, "d" : {"e" : {}}, "f" : {"g" : {}} Output : {'b': {'a': {}}, 'e': {'d': {}}, 'g': {'f': {}} Explanation : Nested dictionaries inverted as outer dictionary keys and viz-a-vis. Input : test_dict = {"a" : {"b" : { "c" : {}}}} Output : {'c': {'b': {'a': {}}}} Explanation : Just a single key, mapping inverted till depth.
Method : Using loop + recursion
This is brute way in which this task can be performed. In this, we extract all the paths from outer to inner for each key using recursion and then use this to reverse the ordering in result.
Python3
# Python3 code to demonstrate working of
# Inversion in nested dictionary
# Using loop + recursion
# utility function to get all paths till end
def extract_path(test_dict, path_way):
if not test_dict:
return [path_way]
temp = []
for key in test_dict:
temp.extend(extract_path(test_dict[key], path_way + [key]))
return temp
# function to compute inversion
def hlper_fnc(test_dict):
all_paths = extract_path(test_dict, [])
res = {}
for path in all_paths:
front = res
for ele in path[::-1]:
if ele not in front :
front[ele] = {}
front = front[ele]
return res
# initializing dictionary
test_dict = {"a" : {"b" : {"c" : {}}},
"d" : {"e" : {}},
"f" : {"g" : {"h" : {}}}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# calling helper function for task
res = hlper_fnc(test_dict)
# printing result
print("The inverted dictionary : " + str(res))
OutputThe original dictionary is : {'a': {'b': {'c': {}}}, 'd': {'e': {}}, 'f': {'g': {'h': {}}}}
The inverted dictionary : {'c': {'b': {'a': {}}}, 'e': {'d': {}}, 'h': {'g': {'f': {}}}}
Using a Stack:
Approach:
Initialize a stack with the input dictionary and a None parent key.
Initialize an empty dictionary for the inverted dictionary.
While the stack is not empty:
a. Pop a dictionary d and its parent key parent_key from the stack.
b. Iterate through the items in the dictionary d.
c. If the parent_key is not None, update the inverted dictionary with the current key k as a key, and a dictionary with the parent_key as a key and an empty dictionary as a value.
d. If the current value v is a dictionary, append it to the stack with the current key k as the parent key.
Output the inverted dictionary.
Python3
# Sample input dictionary
test_dict = {"a": {"b": {}}, "d": {"e": {}}, "f": {"g": {}}}
# Invert the nested dictionary using a stack
stack = [(test_dict, None)]
inverted_dict = {}
while stack:
d, parent_key = stack.pop()
for k, v in d.items():
if parent_key is not None:
inverted_dict.setdefault(k, {}).update({parent_key: {}})
if isinstance(v, dict):
stack.append((v, k))
# Output the inverted dictionary
print(inverted_dict)
Output{'g': {'f': {}}, 'e': {'d': {}}, 'b': {'a': {}}}
This approach has a time complexity of O(n) due to iterating through the dictionary.
The auxiliary space of O(n) to create a new dictionary.
Similar Reads
Python - Sorted Nested Keys in Dictionary Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
4 min read
Key Index in Dictionary - Python We are given a dictionary and a specific key, our task is to find the index of this key when the dictionaryâs keys are considered in order. For example, in {'a': 10, 'b': 20, 'c': 30}, the index of 'b' is 1.Using dictionary comprehension and get()This method builds a dictionary using dictionary comp
2 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
Define a 3 Level Nested Dictionary in Python In Python, dictionaries provide a versatile way to store and organize data. Nested dictionaries, in particular, allow for the creation of multi-level structures. In this article, we'll explore the process of defining a 3-level nested dictionary and demonstrate various methods to achieve this. Define
3 min read
Three Level Nested Dictionary Python In Python, a dictionary is a built-in data type used to store data in key-value pairs. Defined with curly braces `{}`, each pair is separated by a colon `:`. This allows for efficient representation and easy access to data, making it a versatile tool for organizing information. What is 3 Level Neste
4 min read
Loop Through a Nested Dictionary in Python Working with nested dictionaries in Python can be a common scenario, especially when dealing with complex data structures. Iterating through a nested dictionary efficiently is crucial for extracting and manipulating the desired information. In this article, we will explore five simple and generally
3 min read