Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Convert Nested Tuple to Custom Key Dictionary

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

RELATED ARTICLES

Most Popular

Recent Comments