Open In App

Python – Convert Nested dictionary to Mapped Tuple

Last Updated : 24 Feb, 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 convert nested dictionaries to mapped tuple. This kind of problem can occur in web development and day-day programming. Let’s discuss certain ways in which this task can be performed.

Input : test_dict = {‘gfg’ : {‘x’ : 5, ‘y’ : 6, ‘z’: 3}, ‘best’ : {‘x’ : 8, ‘y’ : 3, ‘z’: 5}} Output : [(‘x’, (5, 8)), (‘y’, (6, 3)), (‘z’, (3, 5))] Input : test_dict = {‘gfg’ : {‘x’ : 5, ‘y’ : 6, ‘z’: 3}} Output : [(‘x’, (5, )), (‘y’, (6, )), (‘z’, (3, ))]

Method #1 : Using list comprehension + generator expression The combination of above functions can be used to solve this problem. In this, we perform the tasks of creating the tuple using list comprehension and generator expression helps in grouping, by extracting values using values(). 

Python3




# Python3 code to demonstrate working of
# Convert Nested dictionary to Mapped Tuple
# Using list comprehension + generator expression
 
# initializing dictionary
test_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4},
                                      'best' : {'x' : 8, 'y' : 3}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Nested dictionary to Mapped Tuple
# Using list comprehension + generator expression
res = [(key, tuple(sub[key] for sub in test_dict.values()))
                               for key in test_dict['gfg']]
 
# printing result
print("The grouped dictionary : " + str(res))


Output : The original dictionary is : {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}} The grouped dictionary : [(‘x’, (5, 1, 8)), (‘y’, (6, 4, 3))]

  Method #2 : Using defaultdict() + loop This is yet another way in which this task can be performed. In this, we perform the task of mapping using defaultdict(), of keys of nested dictionaries and recreate value list using loop. This method is useful for older version of Python. 

Python3




# Python3 code to demonstrate working of
# Convert Nested dictionary to Mapped Tuple
# Using defaultdict() + loop
from collections import defaultdict   
 
# initializing dictionary
test_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4},
                                      'best' : {'x' : 8, 'y' : 3}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Nested dictionary to Mapped Tuple
# Using defaultdict() + loop
res = defaultdict(tuple)
for key, val in test_dict.items():
    for ele in val:
        res[ele] += (val[ele], )
 
# printing result
print("The grouped dictionary : " + str(list(res.items()))


Output : The original dictionary is : {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}} The grouped dictionary : [(‘x’, (5, 1, 8)), (‘y’, (6, 4, 3))]

The Time and Space Complexity is the same for both methods:

Time Complexity: O(n2)

Space Complexity: O(n)

Method#3: Using zip() function and dictionary operations

This method uses the zip() function and dictionary operations to convert a nested dictionary to a mapped tuple.

Algorithm:

  1. Initialize an empty list res to store the mapped tuples.
  2. Loop through the keys in the dictionary of interest (here, the dictionary with key ‘gfg’ is chosen as the target dictionary).
  3. For each key, create a tuple of the corresponding values for that key from all sub-dictionaries, using dictionary operations.
  4. Append the tuple to the res list.
  5. Return the res list.

Python




# initializing dictionary
test_dict = {'gfg' : {'x' : 5, 'y' : 6}, 'is' : {'x' : 1, 'y' : 4},
                                      'best' : {'x' : 8, 'y' : 3}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Nested dictionary to Mapped Tuple
# Using zip() function and dictionary operations
res = [(key, tuple(test_dict[k][key] for k in test_dict)) for key in test_dict['gfg']]
 
# printing result
print("The grouped dictionary : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original dictionary is : {'is': {'y': 4, 'x': 1}, 'gfg': {'y': 6, 'x': 5}, 'best': {'y': 3, 'x': 8}}
The grouped dictionary : [('y', (4, 6, 3)), ('x', (1, 5, 8))]

Time complexity: O(NM), where N is the number of keys in the dictionary of interest, and M is the number of sub-dictionaries.

Auxiliary space: O(NM), to store the res list.



Similar Reads

Python - Convert Nested Tuple to Custom Key Dictionary
Sometimes, while working with Python records, we can have data that come without proper column names/identifiers, which can just be identified by their index, but we intend to assign them keys and render in form of dictionaries. This kind of problem can have applications in domains such as web development. Let's discuss certain ways in which this t
4 min read
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 - Column Mapped Tuples to dictionary items
Given Tuple Matrix of length 2, map each column's element value with next column and construct dictionary keys. Input : test_list = [[(1, 4), (6, 3), (4, 7)], [(7, 3), (10, 14), (11, 22)]] Output : {1: 7, 4: 3, 6: 10, 3: 14, 4: 11, 7: 22} Explanation : 1 -> 7, 4 -> 3.., as in same column and indices. Input : test_list = [[(1, 4), (6, 3)], [(7
4 min read
Python - Dictionary Values Mapped Summation
Given a dictionary with a values list, our task is to extract the sum of values, found using mappings. Input : test_dict = {4 : ['a', 'v', 'b', 'e'], 1 : ['g', 'f', 'g'], 3 : ['e', 'v']}, map_vals = {'a' : 3, 'g' : 8, 'f' : 10, 'b' : 4, 'e' : 7, 'v' : 2} Output : {4: 16, 1: 26, 3: 9} Explanation : "g" has 8, "f" has 10 as magnitude, hence 1 is mapp
6 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Python - Convert Tuple to Tuple Pair
Sometimes, while working with Python Tuple records, we can have a problem in which we need to convert Single tuple with 3 elements to pair of dual tuple. This is quite a peculiar problem but can have problems in day-day programming and competitive programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ('A'
10 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
Practice Tags :