Friday, December 27, 2024
Google search engine
HomeLanguagesConvert List of Dictionary to Tuple list Python

Convert List of Dictionary to Tuple list Python

Given a list of dictionaries, write a Python code to convert the list of dictionaries into a list of tuples.
Examples:

Input: 
[{'a':[1, 2, 3], 'b':[4, 5, 6]}, 
 {'c':[7, 8, 9], 'd':[10, 11, 12]}]

Output: 
[('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)]

Below are various methods to convert a list of dictionaries to a list of Python tuples.

Convert List of Dictionary to Tuple list Python Using Naive Approach

Python3




# Python code to demonstrate
# converting list of dictionary to list of tuples
 
# initialising list of dictionary
ini_list = [{'a': [1, 2, 3], 'b':[4, 5, 6]},
            {'c': [7, 8, 9], 'd':[10, 11, 12]}]
 
# converting to list of tuples
temp_dict = {}
 
result = []
 
for ini_dict in ini_list:
 
    # Looking out for keys in dictionary
    for key in ini_dict.keys():
        if key in temp_dict:
            temp_dict[key] += ini_dict[key]
        else:
            temp_dict[key] = ini_dict[key]
 
for key in temp_dict.keys():
    result.append(tuple([key] + temp_dict[key]))
 
# printing result
print("Resultant list of tuples: {}".format(result))


Output

Resultant list of tuples: [('a', 1, 2, 3), ('b', 4, 5, 6), ('c', 7, 8, 9), ('d', 10, 11, 12)]

Time Complexity: O(n*n)
Auxiliary Space: O(n)

This Python code demonstrates how to convert a list of dictionaries into a list of tuples. The initial list of dictionaries, ini_list, contains two dictionaries with keys ‘a’, ‘b’, ‘c’, and ‘d’, each associated with a list of values.

The code initializes an empty dictionary called temp_dict and an empty list called result to store the converted data.

It then iterates through each dictionary in the ini_list. Within each dictionary, it iterates through the keys using ini_dict.keys() to access the keys.

For each key, it checks if it already exists in the temp_dict. If the key exists, it appends the values associated with the key to the existing values in temp_dict[key]. If the key doesn’t exist, it creates a new key-value pair in temp_dict with the key and its associated values.

After processing all the dictionaries in ini_list, the code constructs tuples from the key-value pairs in temp_dict and appends them to the result list. Each tuple consists of the key followed by the associated values.

Finally, the code prints the result list, which contains the desired list of tuples.

Convert List of Dictionary to Tuple list Python Using list comprehension

This Python code converts a list of dictionaries, ini_list, into a list of tuples, dict_list. It uses a list comprehension to iterate over each dictionary in ini_list, and for each key-value pair, constructs a tuple with the key followed by the values. The resulting list of tuples is then printed.

Python3




# Python code to demonstrate
# converting list of dictionary to list of tuples
 
# initialising list of dictionary
ini_list = [{'a': [1, 2, 3], 'b':[4, 5, 6]},
            {'c': [7, 8, 9], 'd':[10, 11, 12]}]
 
# converting to list of tuples
dict_list = [(key, )+tuple(val) for dic in ini_list
             for key, val in dic.items()]
 
# printing result
print("Resultant list of tuples: {}".format(dict_list))


Output:

Resultant list of tuples: [('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)]

Time Complexity: O(n*n) where n is the number of elements in the list “ini_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “ini_list”. 

Convert List of Dictionary to Tuple list Python Using map() function

We first use the map() function to apply a lambda function to each dictionary in the list, which converts each dictionary to a list of tuples. We then flatten the resulting list of lists using a list comprehension, and assign it to the variable dict_list. 

Python3




# Python code to demonstrate
# converting list of dictionary to list of tuples
 
# initialising list of dictionary
ini_list = [{'a': [1, 2, 3], 'b':[4, 5, 6]},
            {'c': [7, 8, 9], 'd':[10, 11, 12]}]
 
# using map() function to convert to list of tuples
dict_list = list(map(lambda d: [(k, )+tuple(v)
                                for k, v in d.items()], ini_list))
 
# flattening the list
dict_list = [t for l in dict_list for t in l]
 
# printing result
print("Resultant list of tuples: {}".format(dict_list))


Output

Resultant list of tuples: [('a', 1, 2, 3), ('b', 4, 5, 6), ('c', 7, 8, 9), ('d', 10, 11, 12)]

Time complexity: O(N*M), where N is the number of dictionaries in the list and M is the maximum number of key-value pairs in any dictionary.
Auxiliary space:  O(N*M), where N is the number of dictionaries in the list and M is the maximum number of key-value pairs in any dictionary.

Using the chain() function from the itertools module with a list comprehension

Approach:

  1. Import the chain() function from the itertools module
  2. Use the chain() function to create a single iterable from the dictionaries in the ini_list
  3. Use a list comprehension to create a list of tuples by combining each key and value pair with the + operator
  4. Flatten the list of tuples

Python3




# Python code to demonstrate
# converting list of dictionary to list of tuples
 
# import the chain function from the itertools module
from itertools import chain
 
# initialising list of dictionary
ini_list = [{'a': [1, 2, 3], 'b':[4, 5, 6]},
            {'c': [7, 8, 9], 'd':[10, 11, 12]}]
 
# using chain() function and list comprehension to convert to list of tuples
tuple_list = [(k,) + tuple(v) for d in ini_list for k, v in chain(d.items())]
 
# printing result
print("Resultant list of tuples: {}".format(tuple_list))


Output

Resultant list of tuples: [('a', 1, 2, 3), ('b', 4, 5, 6), ('c', 7, 8, 9), ('d', 10, 11, 12)]

Time complexity: O(n*m), where n is the number of dictionaries in the list and m is the average number of key-value pairs in each dictionary.
Auxiliary space: O(n*m), to store the tuples in the tuple_list.

RELATED ARTICLES

Most Popular

Recent Comments