Open In App
Related Articles

Python | Convert list of tuples to dictionary value lists

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

# Python3 code to demonstrate working of
# Convert list of tuples to dictionary value lists
# Using defaultdict() + loop
from collections import defaultdict
 
# initializing list
test_list = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using defaultdict() + loop
# Convert list of tuples to dictionary value lists
res = defaultdict(list)
for i, j in test_list:
    res[i].append(j)
 
# printing result
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

# Python3 code to demonstrate working of
# Convert list of tuples to dictionary value lists
# Using defaultdict() + groupby()
from collections import defaultdict
from operator import itemgetter
from itertools import groupby
 
# initializing list
test_list = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using defaultdict() + groupby()
# Convert list of tuples to dictionary value lists
res = dict((k, [v[1] for v in itr]) for k, itr in groupby(
                                test_list, itemgetter(0)))
 
# printing result
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

# Python3 code to demonstrate working of
# Convert list of tuples to dictionary value lists
# Using dict comprehension
 
test_list = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
   
# printing original list
print("The original list is : " + str(test_list))
   
# Using dict comprehension
# Convert list of tuples to dictionary value lists
res = {k: [v for k1, v in test_list if k1 == k] for k, v in test_list}
   
# printing result
print("The merged dictionary is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy

                    

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')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using setdefault
# Convert list of tuples to dictionary value lists
res = {}
for k, v in test_list:
    res.setdefault(k, []).append(v)
 
# printing result
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:

  1. Create an empty dictionary ‘res’.
  2. Loop through each tuple in the ‘test_list’.
  3. If the tuple’s first element is already a key in ‘res’, add the second element of the tuple to the corresponding value list.
  4. 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.
  5. Convert the values of ‘res’ to lists.
  6. Print the resulting dictionary.

Python3

# Python3 code to demonstrate working of
# Convert list of tuples to dictionary value lists
# Using set()
 
# initializing list
test_list = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using set()
# Convert list of tuples to dictionary value lists
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()} # Convert values to lists
 
# printing result
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
 
# initializing list
test_list = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using itertools.groupby()
# Convert list of tuples to dictionary value lists
test_list.sort(key=lambda x: x[0])  # Sort based on the first element (key)
groups = itertools.groupby(test_list, key=lambda x: x[0])  # Group based on the first element (key)
res = {k: [v[1] for v in group] for k, group in groups}  # Convert each group into a dictionary where the key is the first element (key) and the value is a list of second elements (values)
 
# printing result
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

  1. Create a list of tuples test_list with elements (1, ‘gfg’), (1, ‘is’), (2, ‘best’), (3, ‘for’), (4, ‘CS’).
  2. Create an empty dictionary res.
  3. 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.
  4. 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.
  5. 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.
  6. After iterating over all the elements in the list, the dictionary res will contain all the merged key-value pairs.
  7. Print the original list test_list.
  8. Print the merged dictionary res.

Python3

# initializing list
test_list = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]
 
# creating an empty dictionary
res = {}
 
# iterating over the elements in the list
for key, value in test_list:
    # check if key already exists in the dictionary
    if key in res:
        # append the value to the existing list of values for the key
        res[key].append(value)
    else:
        # create a new key-value pair in the dictionary
        res[key] = [value]
 
# printing the original list
print("The original list is: " + str(test_list))
 
# printing the merged dictionary
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. 



Last Updated : 27 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads