Convert List of Dictionary to Tuple list Python
Last Updated :
24 Jun, 2023
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))
OutputResultant 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))
OutputResultant 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:
- Import the chain() function from the itertools module
- Use the chain() function to create a single iterable from the dictionaries in the ini_list
- Use a list comprehension to create a list of tuples by combining each key and value pair with the + operator
- 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))
OutputResultant 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.
Similar Reads
Convert Dictionary to List of Tuples - Python
Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read
Convert List of Lists to Dictionary - Python
We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Convert List of Tuples to Dictionary Value Lists - Python
The task is to convert a list of tuples into a dictionary where the first element of each tuple serves as the key and the second element becomes the value. If a key appears multiple times in the list, its values should be grouped together in a list.For example, given the list li = [(1, 'gfg'), (1, '
4 min read
Convert List of Named Tuples to Dictionary - Python
We are given a list of named tuples we need to convert it into dictionary. For example, given a list li = [d("ojaswi"), d("priyank"), d("sireesha")], the goal is to convert it into a dictionary where each unique key maps to a list of its corresponding values, like {'Name': 'ojaswi'},{'Name': 'priyan
2 min read
Python | Dictionary to list of tuple conversion
Inter conversion between the datatypes is a problem that has many use cases and is usual subproblem in the bigger problem to solve. The conversion of tuple to dictionary has been discussed before. This article discusses a converse case in which one converts the dictionary to list of tuples as the wa
5 min read
Python - Convert List to List of dictionaries
We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read
Python | List of tuples to dictionary conversion
Interconversions are always required while coding in Python, also because of the expansion of Python as a prime language in the field of Data Science. This article discusses yet another problem that converts to dictionary and assigns keys as 1st element of tuple and rest as it's value. Let's discuss
3 min read
Python Convert Dictionary to List of Values
Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read
Python | Convert list of tuples into list
In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Python - Convert Key-Value list Dictionary to List of Lists
We are given a key value list dictionary we need to convert it list of lists. For example we are given a dictionary a = {'name': 'Geeks', 'age': 8, 'city': 'Noida'} we need to convert this into list of lists so the output should be [['name', 'Geeks'], ['age', 25], ['city', 'Geeks']]. Using List Comp
2 min read