Python - Inversion in nested dictionary Last Updated : 27 Mar, 2023 Comments Improve Suggest changes Like Article Like Report See More 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. Create Quiz Comment M manjeet_04 Follow 0 Improve M manjeet_04 Follow 0 Improve Article Tags : Python Python Programs Python dictionary-programs Explore Python FundamentalsPython Introduction 2 min read Input and Output in Python 4 min read Python Variables 4 min read Python Operators 4 min read Python Keywords 2 min read Python Data Types 8 min read Conditional Statements in Python 3 min read Loops in Python - For, While and Nested Loops 5 min read Python Functions 5 min read Recursion in Python 4 min read Python Lambda Functions 5 min read Python Data StructuresPython String 5 min read Python Lists 4 min read Python Tuples 4 min read Python Dictionary 3 min read Python Sets 6 min read Python Arrays 7 min read List Comprehension in Python 4 min read Advanced PythonPython OOP Concepts 11 min read Python Exception Handling 5 min read File Handling in Python 4 min read Python Database Tutorial 4 min read Python MongoDB Tutorial 3 min read Python MySQL 9 min read Python Packages 10 min read Python Modules 3 min read Python DSA Libraries 15 min read List of Python GUI Library and Packages 3 min read Data Science with PythonNumPy Tutorial - Python Library 3 min read Pandas Tutorial 4 min read Matplotlib Tutorial 5 min read Python Seaborn Tutorial 3 min read StatsModel Library - Tutorial 3 min read Learning Model Building in Scikit-learn 6 min read TensorFlow Tutorial 2 min read PyTorch Tutorial 6 min read Web Development with PythonFlask Tutorial 8 min read Django Tutorial | Learn Django Framework 7 min read Django ORM - Inserting, Updating & Deleting Data 4 min read Templating With Jinja2 in Flask 6 min read Django Templates 5 min read Build a REST API using Flask - Python 3 min read Building a Simple API with Django REST Framework 3 min read Python PracticePython Quiz 1 min read Python Coding Practice 1 min read Python Interview Questions and Answers 15+ min read Like