Open In App

Python | Categorize tuple values into dictionary value list

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python, we might face a problem in which we have data in form of list of tuples, and what we intend is, to categorize them into dictionary with a value list of tuples. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using setdefault() + loop 

This task can easily be performed using setdefault(). In this, we just take key and value pair of tuple by iteration and setdafault() is used to assign value to corresponding key of dictionary. 

Python3




# Python3 code to demonstrate working of
# Categorize tuple values into dictionary value list
# Using setdefault() + loop
 
# Initialize list of tuples
test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using setdefault() + loop
# Categorize tuple values into dictionary value list
res = {}
for i, j in test_list:
    res.setdefault(j, []).append(i)
 
# printing result
print("The dictionary converted from tuple list : " + str(res))


Output

The original list : [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
The dictionary converted from tuple list : {3: [1, 2, 5], 4: [1, 6], 2: [3]}

The time complexity of this code is O(n), where n is the length of the input list of tuples.
The auxiliary space of this code is also O(n), where n is the length of the input list of tuples.

Method #2 : Using dict() + list comprehension + frozenset() 

The combination of above methods can be used to perform this particular task. In this, the logical computations are done in comprehension with the help of frozenset() and the container is converted to dictionary using dict(). 

Python3




# Python3 code to demonstrate working of
# Categorize tuple values into dictionary value list
# Using dict() + list comprehension + frozenset()
 
# Initialize list of tuples
test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using dict() + list comprehension + frozenset()
# Categorize tuple values into dictionary value list
res = dict((key, [i[0] for i in test_list if i[1] == key])
           for key in frozenset(j[1] for j in test_list))
 
# printing result
print("The dictionary converted from tuple list : " + str(res))


Output

The original list : [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
The dictionary converted from tuple list : {2: [3], 3: [1, 2, 5], 4: [1, 6]}

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method #3: Using in , not in operators and for loops

Python3




# Python3 code to demonstrate working of
# Categorize tuple values into dictionary value list
 
# Initialize list of tuples
test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
 
# printing original list
print("The original list : " + str(test_list))
 
x = []
for i in test_list:
    if i[1] not in x:
        x.append(i[1])
d = dict()
for i in x:
    a = []
    for j in test_list:
        if(j[1] == i):
            a.append(j[0])
        d[i] = a
 
 
# printing result
print("The dictionary converted from tuple list : " + str(d))


Output

The original list : [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
The dictionary converted from tuple list : {3: [1, 2, 5], 4: [1, 6], 2: [3]}

Method 4 : Converting Tuples to Dictionary using Second Value as Key”

Here are the steps:

Create an empty dictionary result_dict.
Loop through the tuples in test_list.
Get the second value of the tuple as the key for the dictionary and store it in the variable key.
Check if key already exists in result_dict using the in operator. If not, add it to the dictionary with an empty list as the value.
Append the first value of the tuple to the list value of the corresponding key in result_dict.
Print the resulting dictionary.
 

Python3




test_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
 
# create an empty dictionary
result_dict = {}
 
# loop through the tuples in test_list
for tpl in test_list:
    # get the second value of the tuple as the key for the dictionary
    key = tpl[1]
    # if the key does not exist in the dictionary yet, add it with an empty list as the value
    if key not in result_dict:
        result_dict[key] = []
    # append the first value of the tuple to the list value of the corresponding key
    result_dict[key].append(tpl[0])
 
# print the result dictionary
print("The dictionary converted from tuple list : " + str(result_dict))


Output

The dictionary converted from tuple list : {3: [1, 2, 5], 4: [1, 6], 2: [3]}

The time complexity of this method is O(n) where n is the number of tuples in test_list. 

The auxiliary space required is also O(n) to store the result dictionary.

METHOD 5:Using itertools.

APPROACH:

The program sorts a given list of tuples based on the second element of each tuple, and then categorizes the tuples into a dictionary where the keys are the unique second elements of the tuples, and the values are the corresponding first elements of the tuples.

ALGORITHM:

1. Import the “groupby” function from the itertools module
2. Define the given list of tuples
3. Sort the list of tuples based on the second element of each tuple using a lambda function as the key argument to the sort method.
4. Create an empty dictionary to store the categorized tuples
5. Iterate over each group of tuples that have the same second element using the groupby function, and create a key in the dictionary for each unique second element. The corresponding value is a list of the first elements from each tuple in the group.
6. Print the resulting dictionary.

Python3




from itertools import groupby
 
tuple_list = [(1, 3), (1, 4), (2, 3), (3, 2), (5, 3), (6, 4)]
 
tuple_list.sort(key=lambda x: x[1])
 
result = {}
 
for key, group in groupby(tuple_list, lambda x: x[1]):
    result[key] = [x[0] for x in group]
 
print(result)


Output

{2: [3], 3: [1, 2, 5], 4: [1, 6]}

Time complexity: O(nlogn) (sorting takes nlogn time, and iterating over the list takes linear time)
Space complexity: O(n) (for the resulting dictionary)



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