One among the problem of interconversion of data types in python is conversion of list of tuples to dictionaries, in which the keys are 1st elements of tuple, which are uniquely identified as keys in dictionary and it’s corresponding value as a list of the corresponding value of respective keys as tuple’s second element. Let’s discuss how to solve this particular problem.
Convert list of tuples to dictionary value lists Using defaultdict() + loop
This problem can easily be solved using the defaultdict() and loop. The defaultdict provides a default value dictionary container to assign corresponding value list to keys, so that we don’t need to initialize keys with empty list and loop is used to extract like values from tuple.
Python3
from collections import defaultdict
test_list = [( 1 , 'gfg' ), ( 1 , 'is' ), ( 2 , 'best' ), ( 3 , 'for' ), ( 4 , 'CS' )]
print ( "The original list is : " + str (test_list))
res = defaultdict( list )
for i, j in test_list:
res[i].append(j)
print ( "The merged dictionary is : " + str ( dict (res)))
|
Output
The original list is : [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
The merged dictionary is : {1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}
Time complexity: O(n), where n is the number of tuples in the input list. This is because the program iterates through each tuple in the input list once to create the dictionary.
Auxiliary space: O(n), where n is the number of tuples in the input list.
Convert list of tuples to dictionary value lists Using defaultdict() + groupby()
This method performs the task similar to above method, just instead of using loop to access each key value pair, here we use Python’s groupby library to group keys with value and convert then into a list.
Python3
from collections import defaultdict
from operator import itemgetter
from itertools import groupby
test_list = [( 1 , 'gfg' ), ( 1 , 'is' ), ( 2 , 'best' ), ( 3 , 'for' ), ( 4 , 'CS' )]
print ( "The original list is : " + str (test_list))
res = dict ((k, [v[ 1 ] for v in itr]) for k, itr in groupby(
test_list, itemgetter( 0 )))
print ( "The merged dictionary is : " + str ( dict (res)))
|
Output
The original list is : [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
The merged dictionary is : {1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}
Time complexity: O(n)
Auxiliary Space: O(n)
Convert list of tuples to dictionary value lists Using dict comprehension
This method uses dict comprehension to create a dictionary from the list of tuples. This approach is similar to the first method, but the code is shorter and more readable.
Python3
test_list = [( 1 , 'gfg' ), ( 1 , 'is' ), ( 2 , 'best' ), ( 3 , 'for' ), ( 4 , 'CS' )]
print ( "The original list is : " + str (test_list))
res = {k: [v for k1, v in test_list if k1 = = k] for k, v in test_list}
print ( "The merged dictionary is : " + str (res))
|
Output
The original list is : [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
The merged dictionary is : {1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}
Time complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list
Convert list of tuples to dictionary value lists Using setdefault
Use setdefault method of dictionary to create a dictionary with default value as list and then append the values to the list based on the key.
Python3
test_list = [( 1 , 'gfg' ), ( 1 , 'is' ), ( 2 , 'best' ), ( 3 , 'for' ), ( 4 , 'CS' )]
print ( "The original list is : " + str (test_list))
res = {}
for k, v in test_list:
res.setdefault(k, []).append(v)
print ( "The merged dictionary is : " + str (res))
|
Output
The original list is : [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
The merged dictionary is : {1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}
Time Complexity: O(n), where n is the length of the input list. This is because the program iterates over the input list once to create the dictionary using setdefault.
Auxiliary Space: O(n), where n is the length of the input list. This is because the program creates a dictionary with one key and a list of values for each key in the input list.
Convert list of tuples to dictionary value lists Using set() function
Here is another approach to convert the list of tuples to dictionary value lists using the set() function.
Step-by-step approach:
- Create an empty dictionary ‘res’.
- Loop through each tuple in the ‘test_list’.
- If the tuple’s first element is already a key in ‘res’, add the second element of the tuple to the corresponding value list.
- If the tuple’s first element is not already a key in ‘res’, create a new key-value pair where the key is the first element of the tuple and the value is a set containing the second element of the tuple.
- Convert the values of ‘res’ to lists.
- Print the resulting dictionary.
Python3
test_list = [( 1 , 'gfg' ), ( 1 , 'is' ), ( 2 , 'best' ), ( 3 , 'for' ), ( 4 , 'CS' )]
print ( "The original list is : " + str (test_list))
res = {}
for i, j in test_list:
if i in res:
res[i].add(j)
else :
res[i] = set ([j])
res = {k: list (v) for k, v in res.items()}
print ( "The merged dictionary is : " + str (res))
|
Output
The original list is : [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
The merged dictionary is : {1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}
Time complexity: O(n), where n is the number of tuples in ‘test_list’.
Auxiliary space: O(n), where n is the number of tuples in ‘test_list’.
Convert list of tuples to dictionary value lists Using itertools.groupby()
This method uses itertools.groupby() function to group the list of tuples based on the first element (key) and then convert each group into a dictionary where the key is the first element (key) and the value is a list of second elements (values).
Step-by-step approach:
Import itertools module.
Sort the list of tuples based on the first element (key).
Use itertools.groupby() to group the list of tuples based on the first element (key).
Create a dictionary where each key is the first element (key) of each group and the value is a list of second elements (values) of each group.
Return the dictionary as a result.
Python3
import itertools
test_list = [( 1 , 'gfg' ), ( 1 , 'is' ), ( 2 , 'best' ), ( 3 , 'for' ), ( 4 , 'CS' )]
print ( "The original list is : " + str (test_list))
test_list.sort(key = lambda x: x[ 0 ])
groups = itertools.groupby(test_list, key = lambda x: x[ 0 ])
res = {k: [v[ 1 ] for v in group] for k, group in groups}
print ( "The merged dictionary is : " + str (res))
|
Output
The original list is : [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
The merged dictionary is : {1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}
Time complexity: O(n log n) – due to the sorting operation.
Auxiliary space: O(n) – to store the dictionary.
Convert list of tuples to dictionary value lists using a traditional loop and dictionary
- Create a list of tuples test_list with elements (1, ‘gfg’), (1, ‘is’), (2, ‘best’), (3, ‘for’), (4, ‘CS’).
- Create an empty dictionary res.
- Iterate over the elements in the list test_list using a loop. Each element in the list is a tuple with two values, a key and a value.
- Check if the key already exists in the dictionary res using the in keyword. If the key already exists, then append the value to the existing list of values for that key.
- If the key doesn’t exist in the dictionary, then create a new key-value pair where the key is the current key and the value is a list containing only the current value.
- After iterating over all the elements in the list, the dictionary res will contain all the merged key-value pairs.
- Print the original list test_list.
- Print the merged dictionary res.
Python3
test_list = [( 1 , 'gfg' ), ( 1 , 'is' ), ( 2 , 'best' ), ( 3 , 'for' ), ( 4 , 'CS' )]
res = {}
for key, value in test_list:
if key in res:
res[key].append(value)
else :
res[key] = [value]
print ( "The original list is: " + str (test_list))
print ( "The merged dictionary is: " + str (res))
|
Output
The original list is: [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
The merged dictionary is: {1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}
Time Complexity: The time complexity of this method is O(n), where n is the length of the input list test_list.
Auxiliary Space: The auxiliary space complexity is O(n), where n is the length of the input list test_list.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Jul, 2023
Like Article
Save Article