Open In App

Python – Convert Nested Tuple to Custom Key Dictionary

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

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 task can be performed.

Input : test_tuple = ((1, ‘Gfg’, 2), (3, ‘best’, 4)), keys = [‘key’, ‘value’, ‘id’] 
Output : [{‘key’: 1, ‘value’: ‘Gfg’, ‘id’: 2}, {‘key’: 3, ‘value’: ‘best’, ‘id’: 4}] 

Input : test_tuple = test_tuple = ((1, ‘Gfg’), (2, 3)), keys = [‘key’, ‘value’] 
Output : [{‘key’: 1, ‘value’: ‘Gfg’}, {‘key’: 2, ‘value’: 3}]

Method #1 : Using list comprehension + dictionary comprehension The combination of above functionalities can be used to solve this problem. In this, we perform the task of assigning keys using dictionary comprehension and iteration of all keys and constructing data using list comprehension. 

Python3




# Python3 code to demonstrate working of
# Convert Nested Tuple to Custom Key Dictionary
# Using list comprehension + dictionary comprehension
 
# initializing tuple
test_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Convert Nested Tuple to Custom Key Dictionary
# Using list comprehension + dictionary comprehension
res = [{'key': sub[0], 'value': sub[1], 'id': sub[2]}
                            for sub in test_tuple]
 
# printing result
print("The converted dictionary : " + str(res))


Output

The original tuple : ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
The converted dictionary : [{'key': 4, 'value': 'Gfg', 'id': 10}, {'key': 3, 'value': 'is', 'id': 8}, {'key': 6, 'value': 'Best', 'id': 10}]

Time complexity: O(n), where n is the number of tuples in the input nested tuple.
Auxiliary space: O(n), where n is the number of tuples in the input nested tuple. 

Method #2: Using zip() + list comprehension The combination of above functions can be used to solve this problem. In this, we assign index wise keys using list content and mapping using zip(). In this, flexibility of predefining/scaling keys is provided. 

Python3




# Python3 code to demonstrate working of
# Convert Nested Tuple to Custom Key Dictionary
# Using zip() + list comprehension
 
# initializing tuple
test_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# initializing Keys
keys = ['key', 'value', 'id']
 
# Convert Nested Tuple to Custom Key Dictionary
# Using zip() + list comprehension
res = [{key: val for key, val in zip(keys, sub)}
                        for sub in test_tuple]
 
# printing result
print("The converted dictionary : " + str(res))


Output

The original tuple : ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
The converted dictionary : [{'key': 4, 'value': 'Gfg', 'id': 10}, {'key': 3, 'value': 'is', 'id': 8}, {'key': 6, 'value': 'Best', 'id': 10}]

Time complexity: O(n), where n is the number of elements in the tuple
Auxiliary space: O(n), where n is the number of elements in the tuple.

Method #3: Using a for loop

  1. Initialize a tuple named ‘test_tuple’ with nested tuples as its elements.
  2. Initialize a list named ‘keys’ containing the desired keys for the output dictionary.
  3. Initialize an empty list named ‘res’ to store the resulting dictionaries.
  4. Start a for loop to iterate over each nested tuple in ‘test_tuple’.
  5. For each nested tuple, initialize an empty dictionary named ‘sub_dict’.
  6. Start a nested for loop using the range function to iterate over the range of length of ‘keys’.
  7. For each iteration of the nested for loop, assign a key-value pair to the ‘sub_dict’ dictionary using the current key from ‘keys’ and the current value from the current nested tuple.
  8. Append the ‘sub_dict’ dictionary to the ‘res’ list.
  9. Once the for loop finishes, print the resulting ‘res’ list of dictionaries as a string with a message.

Python3




# initializing tuple
test_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
 
# initializing keys
keys = ['key', 'value', 'id']
 
# initializing result dictionary
res = []
 
# iterate over the tuple and construct the dictionary
for sub in test_tuple:
    sub_dict = {}
    for i in range(len(keys)):
        sub_dict[keys[i]] = sub[i]
    res.append(sub_dict)
 
# printing result
print("The converted dictionary : " + str(res))


Output

The converted dictionary : [{'key': 4, 'value': 'Gfg', 'id': 10}, {'key': 3, 'value': 'is', 'id': 8}, {'key': 6, 'value': 'Best', 'id': 10}]

Time complexity: The time complexity of this approach is O(nm), where n is the number of tuples in the input tuple and m is the number of elements in each tuple.

Auxiliary space: The auxiliary space required by the code is O(nm), where n is the number of tuples in the input tuple and m is the number of elements in each tuple.



Similar Reads

Python - Custom Tuple Key Summation in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform group summation of values, of certain key on particular index of tuple keys of dictionary. This problem is quite custom, but can have application in domains that revolves around data processing. Let's discuss certain ways in which this task can be p
7 min read
Python - Convert Nested dictionary to Mapped Tuple
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' :
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 - Convert tuple list to dictionary with key from a given start value
Given a tuple list, the following article focuses on how to convert it to a dictionary, with keys starting from a specified start value. This start value is only to give a head start, next keys will increment the value of their previous keys. Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10, 1)], start = 4 Output : {4: (4, 5), 5: (1, 3), 6:
4 min read
Python - Summation of Custom nested keys in Dictionary
Given a dictionary with keys as nested dictionaries, find the sum of values of certain custom keys inside the nested dictionary. Input : test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12}, 'is' : {1 : 9, 5: 7, 9: 2}, 'best' : {1 : 3, 5: 4, 9: 14}}, sum_key = [1] Output : 18 Explanation : 6 + 9 + 3 = 18, only values with key 1 are summed. Input : test_dict =
10 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 | 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 - Remove K valued key from Nested Dictionary
Sometimes, while working with records, we can have a problem in which we need to perform the removal of a key from nested dictionary whose value us specific to K. This is a common problem and has its application in data domains such as web development. Lets discuss certain ways in which this task can be performed. Input : test_dict = {'CS': {'price
8 min read
Python - Unnest single Key Nested Dictionary List
Sometimes, while working with Python data, we can have a problem in which we need to perform unnesting of all the dictionaries which have single nesting of keys, i.e a single key and value and can easily be pointed to outer key directly. This kind of problem is common in domains requiring data optimization. Let's discuss certain ways in which this
7 min read
three90RightbarBannerImg