Python | Group tuple into list based on value
Last Updated :
13 Apr, 2023
Sometimes, while working with Python tuples, we can have a problem in which we need to group tuple elements to nested list on basis of values allotted to it. This can be useful in many grouping applications. Let's discuss certain ways in which this task can be performed.
Method #1 : Using itemgetter() + list comprehension + groupby()
The combination of above functions can be used to perform this task. In this, we access the value using itemgetter() and logic for grouping is performed using groupby() and list comprehension.
Python3
# Python3 code to demonstrate working of
# Group tuple into list based on value
# using itemgetter() + list comprehension + groupby()
from operator import itemgetter
from itertools import groupby
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
# printing original list
print("The original list : " + str(test_list))
# Group tuple into list based on value
# using itemgetter() + list comprehension + groupby()
res = [[i for i, j in temp]\
for key, temp in groupby(test_list, key = itemgetter(1))]
# printing result
print("The list after grouping by value : " + str(res))
OutputThe original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using map() + itemgetter() + groupby() + list comprehension
This method is similar to the above method, the only difference is that we chose a map for the formation of keys as nested list for formation of new resultant lists.
Python3
# Python3 code to demonstrate working of
# Group tuple into list based on value
# using map() + itemgetter() + groupby() + list comprehension
from operator import itemgetter
from itertools import groupby
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
# printing original list
print("The original list : " + str(test_list))
# Group tuple into list based on value
# using map() + itemgetter() + groupby() + list comprehension
res = [list(map(itemgetter(0), temp))
for (key, temp) in groupby(test_list, itemgetter(1))]
# printing result
print("The list after grouping by value : " + str(res))
OutputThe original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]
The time complexity of this approach is O(n log n) due to sorting by the itemgetter() function. The groupby() function and the list comprehension run in linear time.
The auxiliary space complexity is O(n) for the list used to store the grouped tuples, where n is the length of the input list.
Method #3 : Using defaultdict()
This method uses the defaultdict() from the collections module to group the tuples based on the second element of the tuple as the key and the first element as the value. The result is then transformed into a list of lists using list comprehension.
Python3
# Python3 code to demonstrate working of
# Group tuple into list based on value
# using defaultdict() + list comprehension
from collections import defaultdict
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
# printing original list
print("The original list : " + str(test_list))
# Group tuple into list based on value
# using defaultdict() + list comprehension
temp = defaultdict(list)
for i, j in test_list:
temp[j].append(i)
res = [temp[i] for i in temp]
# printing result
print("The list after grouping by value : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]
Time complexity: O(n)
Auxiliary Space : O(n)
Method 4: using the itertools module's groupby() function:
Approach:
- Import the itertools module.
- Initialize the list with tuples.
- Sort the list based on the second element of each tuple using the sorted() function with a lambda function as the key.
- Use the groupby() function from the itertools module to group the sorted list based on the second element of each tuple. We also use a lambda function to get the second element as the key.
- Iterate through each group and append the first element of each tuple to a list.
- Print the result.
Python3
# import itertools module
import itertools
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
# printing original list
print("The original list : " + str(test_list))
# Group tuple into list based on value
# using itertools.groupby() function
temp = itertools.groupby(
sorted(test_list, key=lambda x: x[1]), key=lambda x: x[1])
res = [[i[0] for i in g] for k, g in temp]
# printing result
print("The list after grouping by value : " + str(res))
OutputThe original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[5, 6, 8], [1, 2], [6]]
Time complexity: O(nlogn), where n is the number of tuples in the list. We need to sort the list before using the groupby() function.
Auxiliary space: O(n), where n is the number of tuples in the list. We need to store the values in a list.
Method #5: Using dictionary and for loop
Step-by-step approach:
- Create an empty dictionary to store the grouped tuples
- Loop through the tuples in the list
- Get the second element of the tuple
- If the key is not already in the dictionary, add it to an empty list as value
- Append the current tuple to the list corresponding to the key in the dictionary
- Convert the dictionary values to lists and store in res
- Printing result
Below is the implementation of the above approach:
Python3
# initialize list
test_list = [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
# printing original list
print("The original list : " + str(test_list))
# create an empty dictionary to store the grouped tuples
grouped_dict = {}
# loop through the tuples in the list
for tup in test_list:
# get the second element of the tuple
key = tup[1]
# if the key is not already in the dictionary, add it with an empty list as value
if key not in grouped_dict:
grouped_dict[key] = []
# append the current tuple to the list corresponding to the key in the dictionary
grouped_dict[key].append(tup[0])
# convert the dictionary values to lists and store in res
res = [v for k, v in grouped_dict.items()]
# printing result
print("The list after grouping by value : " + str(res))
OutputThe original list : [(1, 4), (2, 4), (6, 7), (5, 1), (6, 1), (8, 1)]
The list after grouping by value : [[1, 2], [6], [5, 6, 8]]
Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list, to store the grouped dictionary.
Similar Reads
Python | Group tuples in list with same first value
Given a list of tuples, the task is to print another list containing tuple of same first element. Below are some ways to achieve above tasks. Example: Input : [('x', 'y'), ('x', 'z'), ('w', 't')] Output: [('w', 't'), ('x', 'y', 'z')] Method #1: Using extend Python3 # Python code to find common # fir
7 min read
Python - Minimum in tuple list value
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the minimum of list as tuple attribute. Letâs discuss certai
5 min read
Python - Value nested grouping on List
Sometimes, while working with data, we can have a problem in which we have flat data in the form of a list of dictionaries, and we need to perform the categorization from that bare dictionaries according to ids. This can have applications in domains that involve data, such as web development and Dat
6 min read
Python | Add tuple to front of list
Sometimes, while working with Python list, we can have a problem in which we need to add a new tuple to existing list. Append at rear is usually easier than addition at front. Let's discuss certain ways in which this task can be performed. Method #1 : Using insert() This is one of the way in which t
7 min read
Python - Group single item dictionaries into List values
Given a List of single-item dictionaries, group them into dictionary value lists according to similar values. Input : [{"Gfg" : 3}, {"is": 8}, {"Gfg": 18}, {"Best": 33}]Output : {'Gfg': [3, 18], 'is': [8], 'Best': [33]} Explanation : Each key converted to list values and dictionary. Input : [{"Gfg"
6 min read
Python | Grouping list values into dictionary
Sometimes, while working with data, we can be encountered a situation in which we have a list of lists and we need to group its 2nd index with the common initial element in lists. Let's discuss ways in which this problem can be solved. Method 1: Using defaultdict() + loop + dict() The defaultdict ca
7 min read
Split list into lists by value - Python
The goal here is to split a list into sublists based on a specific value in Python. For example, given a list [1, 4, 5, 6, 4, 7, 4, 8] and a chosen value 4, we want to split the list into segments that do not contain the value 4, such as [[1], [5, 6], [7], [8]]. Letâs explore different approaches to
4 min read
Python Group by matching second tuple value in list of tuples
Given a list of tuples, the task is to group the tuples by matching the second element in the tuples. We can achieve this using dictionary by checking the second element in each tuple. Examples: Input : [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)] Output: {80: [(20, 80), (31, 80)], 11: [(88, 11
3 min read
Python - Group keys to values list
Sometimes, while working with Python dictionaries, we can have problem in which we need to find all possible values of all keys in a dictionary. This utility is quite common and can occur in many domains including day-day programming and school programming. Lets discuss certain way in which this tas
5 min read
Python - Tuple key detection from value list
Sometimes, while working with record data, we can have a problem in which we need to extract the key which has matching value of K from its value list. This kind of problem can occur in domains that are linked to data. Lets discuss certain ways in which this task can be performed. Method #1 : Using
6 min read