Monday, November 18, 2024
Google search engine
HomeLanguagesPython Program to Convert Tuple Value List to List of Tuples

Python Program to Convert Tuple Value List to List of Tuples

Given a dictionary with values as a tuple list, convert it to a key-mapped list of tuples.

Input : test_dict = {'Gfg' : [(5, ), (6, )], 'is' : [(5, )], 'best' :[(7, )]} 
Output : [('Gfg', 5), ('Gfg', 6), ('is', 5), ('best', 7)] 
Explanation : Keys grouped with values.

Convert Tuple Value List to List of Tuples Using loop + * operator + items()

This is one of the ways in which this task can be performed. In this, we iterate for all the keys using loop and map keys with all values by unpacking all values in tuple using * operator.

Python3




# Python3 code to demonstrate working of
# Convert Tuple value list to List of tuples
# Using loop + * operator + items()
 
# initializing dictionary
test_dict = {'Gfg' : [(5, 6, 7), (1, 3), (6, )],
             'is' : [(5, 5, 2, 2, 6)],
             'best' :[(7, ), (9, 16)]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using items() to extract all the items of
# dictionary
res = []
for key, val in test_dict.items():
    for ele in val:
        res.append((key, *ele))
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original dictionary is : {'Gfg': [(5, 6, 7), (1, 3), (6,)], 'is': [(5, 5, 2, 2, 6)], 'best': [(7,), (9, 16)]}
The converted tuple list : [('Gfg', 5, 6, 7), ('Gfg', 1, 3), ('Gfg', 6), ('is', 5, 5, ...

Time Complexity: O(n*n) where n is the number of elements in the dictionary.
Auxiliary Space: O(n), where n is the number of elements in the dictionary.

Convert Tuple Value List to List of Tuples Using list comprehension + * operator + items()

This is yet another way to solve this problem. Solves in a similar way as the above method. The only difference offering a one-liner solution using list comprehension.

Python3




# Python3 code to demonstrate working of
# Convert Tuple value list to List of tuples
# Using list comprehension + * operator + items()
 
# initializing dictionary
test_dict = {'Gfg' : [(5, 6, 7), (1, 3), (6, )],
             'is' : [(5, 5, 2, 2, 6)],
             'best' :[(7, ), (9, 16)]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# list comprehension encapsulates whole logic
# into one line
res = [(key, *ele) for key, sub in test_dict.items() for ele in sub]
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original dictionary is : {'Gfg': [(5, 6, 7), (1, 3), (6,)], 'is': [(5, 5, 2, 2, 6)], 'best': [(7,), (9, 16)]}
The converted tuple list : [('Gfg', 5, 6, 7), ('Gfg', 1, 3), ('Gfg', 6), ('is', 5, 5, ...

Time Complexity: O(n), where n is the values in dictionary
Auxiliary Space: O(n), where n is the size of dictionary

Convert Tuple Value List to List of Tuples Using nested list comprehension

  • Initialize the dictionary test_dict with the given values.
  • Print the original dictionary.
  • Use a nested list comprehension to convert tuple value list to list of tuples:
    • for key, val_list in test_dict.items(): Iterate over the key-value pairs in the dictionary.
    • for val_tuple in val_list: Iterate over each tuple in the value list for the current key.
    • (key, *val_tuple): Create a tuple with the current key followed by the values in the current tuple. The * operator is used to unpack the values in the tuple.
  • Store the result in the variable res.
  • Print the converted tuple list.

Python3




# Python3 code to demonstrate working of
# Convert Tuple value list to List of tuples
# Using nested list comprehension
 
# initializing dictionary
test_dict = {'Gfg' : [(5, 6, 7), (1, 3), (6, )],
             'is' : [(5, 5, 2, 2, 6)],
             'best' :[(7, ), (9, 16)]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using nested list comprehension to
# convert tuple value list to list of tuples
res = [(key, *val_tuple) for key, val_list in test_dict.items() for val_tuple in val_list]
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original dictionary is : {'Gfg': [(5, 6, 7), (1, 3), (6,)], 'is': [(5, 5, 2, 2, 6)], 'best': [(7,), (9, 16)]}
The converted tuple list : [('Gfg', 5, 6, 7), ('Gfg', 1, 3), ('Gfg', 6), ('is', 5, 5, 2, 2, 6), ('best', 7), ('best', 9, 16)]

Time Complexity: O(N*M, 
where N is the number of key-value pairs in the dictionary and m is maximum number of tuples in the value lists of all key-value pairs combined.
Auxiliary Space: O(N*M), 
where N is the number of key-value pairs in the dictionary and M is maximum number of tuples in the value lists of all key-value pairs combined.

Convert Tuple Value List to List of Tuples Using the Recursive method

The algorithm is as follows:

  • Check if the dictionary is empty. If so, return the result list.
  • Pop an item from the dictionary, which consists of a key-value pair.
  • Iterate over the values of the item, and for each value, create a new tuple consisting of the key and the value’s elements unpacked.
  • Append the new tuple to the result list.
  • Recursively call the function with the updated dictionary and result list.
  • Return the final result list.

Python3




def tupleListToListOfTuples(d, res=[]):
    if not d:
        return res
    else:
        key, val = d.popitem()
        for v in val:
            res.append((key, *v))
        return tupleListToListOfTuples(d, res)
 
# Driver code
test_dict = {'Gfg': [(5, 6, 7), (1, 3), (6,)],
             'is': [(5, 5, 2, 2, 6)],
             'best': [(7,), (9, 16)]}
print("The original dictionary is:", test_dict)
 
res = tupleListToListOfTuples(test_dict)
print("The converted tuple list:", res)


Output

The original dictionary is: {'Gfg': [(5, 6, 7), (1, 3), (6,)], 'is': [(5, 5, 2, 2, 6)], 'best': [(7,), (9, 16)]}
The converted tuple list: [('best', 7), ('best', 9, 16), ('is', 5, 5, 2, 2, 6), ('Gfg', 5, 6, 7), ('Gfg', 1, 3), ('Gfg', 6)]

Time complexity: O(n), Where n is the total number of elements in all the lists in the dictionary. 
Auxiliary Space: O(n), As the function uses recursion and creates a new list to store the result.

Convert Tuple Value List to List of Tuples Using map() and lambda function

Step-by-step approach:

  • Define a dictionary named test_dict that contains keys with corresponding values being lists of tuples.
  • Print the original dictionary using the print() function.
  • Use the map() function and a lambda function to iterate over each key-value pair in test_dict. For each key-value pair, create a new list of tuples that contains the key as the first element followed by the elements of each tuple in the value list using the * operator to unpack the tuple. This creates a nested list of lists of tuples.
  • Convert the nested list into a flat list using a list comprehension that iterates over each sublist in the nested list and each tuple in each sublist and appends each tuple to a new list named res.
  • Print the final result using the print() function. The res list contains the converted tuple list.

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {'Gfg': [(5, 6, 7), (1, 3), (6,)],
             'is': [(5, 5, 2, 2, 6)],
             'best': [(7,), (9, 16)]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using map() and lambda function to extract all the items of dictionary
res = list(map(lambda x: [(x[0], *y) for y in x[1]], test_dict.items()))
 
# flattening the result
res = [item for sublist in res for item in sublist]
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original dictionary is : {'Gfg': [(5, 6, 7), (1, 3), (6,)], 'is': [(5, 5, 2, 2, 6)], 'best': [(7,), (9, 16)]}
The converted tuple list : [('Gfg', 5, 6, 7), ('Gfg', 1, 3), ('Gfg', 6), ('is', 5, 5, 2, 2, 6), ('best', 7), ('best', 9, 16)]

Time Complexity: O(n*m), where n is the number of keys in the dictionary and m is the length of the largest list value in the dictionary.
Auxiliary Space: O(n*m), as we need to store the result in a list.

Convert Tuple Value List to List of Tuples Using a dictionary comprehension. 

Step-by-step approach:

  • Use a dictionary comprehension to create a new dictionary where the keys are the same as the original dictionary and the values are the result of using a list comprehension to convert each list of tuples to a list of tuples with the key prepended to each tuple.
  • Use the values of the new dictionary to create a flattened list of tuples.
  • Print the result.

Python3




# initializing dictionary
test_dict = {'Gfg': [(5, 6, 7), (1, 3), (6,)],
             'is': [(5, 5, 2, 2, 6)],
             'best': [(7,), (9, 16)]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using dictionary comprehension to prepend key to each tuple
prepended_dict = {k: [(k, *t) for t in v] for k, v in test_dict.items()}
 
# flattening the result
res = [item for sublist in prepended_dict.values() for item in sublist]
 
# printing result
print("The converted tuple list : " + str(res))


Output

The original dictionary is : {'Gfg': [(5, 6, 7), (1, 3), (6,)], 'is': [(5, 5, 2, 2, 6)], 'best': [(7,), (9, 16)]}
The converted tuple list : [('Gfg', 5, 6, 7), ('Gfg', 1, 3), ('Gfg', 6), ('is', 5, 5, 2, 2, 6), ('best', 7), ('best', 9, 16)]

Time complexity: O(nm), where n is the number of keys in the dictionary and m is the average length of the lists of tuples.
Auxiliary space: O(nm), to store the new dictionary and the flattened list of tuples.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments