Open In App

Python – Inversion in nested dictionary

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

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))


Output

The 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 | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python - Color Inversion using Pillow
Color Inversion (Image Negative) is the method of inverting pixel values of an image. Image inversion does not depend on the color mode of the image, i.e. inversion works on channel level. When inversion is used on a multi color image (RGB, CMYK etc) then each channel is treated separately, and the final result if formed by calibrating the results
4 min read
Python Nested Dictionary
A Dictionary in Python works similarly to the Dictionary in the real world. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. What is Python in Nested Dictionary? Nesting Dictionary means putting a dictionary inside another dictionary. Ne
3 min read
Python | Sum values for each key in nested dictionary
Given a nested dictionary and we have to find sum of particular value in that nested dictionary. This is basically useful in cases where we are given a JSON object or we have scraped a particular page and we want to sum the value of a particular attribute in objects. Code #1: Find sum of sharpness values using sum() function Step-by-step approach:
2 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 | Sort nested dictionary by key
Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed. Method #1 : Using OrderedDict() + sorted() This task
4 min read
Python | Add keys to nested dictionary
Addition of keys in dictionaries have been discussed many times, but sometimes, we might have a problem in which we require to alter/add keys in the nested dictionary. This type of problem is common in today's world with advent of NoSQL databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using for loop Step-by-step
5 min read
Python | Safe access nested dictionary keys
Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let's discuss certain ways to safely get the nested available key in dictionary. Method #1 : Using nested ge
3 min read
Practice Tags :