Python – Group first elements by second elements in Tuple list
Last Updated :
17 Apr, 2023
Given List of tuples, group 1st elements on basis of 2nd elements.
Input : test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (3, 7)]
Output : {5: [6, 2], 7: [2, 8, 3]}
Explanation : 5 occurs along with 6 and 2 in tuple list, hence grouping.
Input : test_list = [(6, 5), (2, 7), (2, 5), (8, 7)]
Output : {5: [6, 2], 7: [2, 8]}
Explanation : 5 occurs along with 6 and 2 in tuple list, hence grouping.
Method #1 : Using loop + groupby() + sorted() + list comprehension + lambda
In this, the elements are sorted for grouping, function provided by lambda, then only first elements are extracted using list comprehension out of result. And final dictionary formation using loop.
Python3
from itertools import groupby
test_list = [( 6 , 5 ), ( 2 , 7 ), ( 2 , 5 ), ( 8 , 7 ), ( 9 , 8 ), ( 3 , 7 )]
print ( "The original list is : " + str (test_list))
res = dict ()
for key, val in groupby( sorted (test_list, key = lambda ele: ele[ 1 ]), key = lambda ele: ele[ 1 ]):
res[key] = [ele[ 0 ] for ele in val]
print ( "Grouped Dictionary : " + str (res))
|
Output
The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Grouped Dictionary : {5: [6, 2], 7: [2, 8, 3], 8: [9]}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using dictionary comprehension
This is method similar to above, just a one-liner shorthand handled using dictionary comprehension.
Python3
from itertools import groupby
test_list = [( 6 , 5 ), ( 2 , 7 ), ( 2 , 5 ), ( 8 , 7 ), ( 9 , 8 ), ( 3 , 7 )]
print ( "The original list is : " + str (test_list))
res = {key: [v[ 0 ] for v in val] for key, val in groupby(
sorted (test_list, key = lambda ele: ele[ 1 ]), key = lambda ele: ele[ 1 ])}
print ( "Grouped Dictionary : " + str (res))
|
Output
The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Grouped Dictionary : {5: [6, 2], 7: [2, 8, 3], 8: [9]}
Time Complexity: O(nlogn) for sorting the list, where n is the length of the input list.
Auxiliary Space: O(n) for storing the dictionary.
Method #3 : Using for loop , in and not in operators
Python3
test_list = [( 6 , 5 ), ( 2 , 7 ), ( 2 , 5 ), ( 8 , 7 ), ( 9 , 8 ), ( 3 , 7 )]
print ( "The original list is : " + str (test_list))
res = dict ()
x = []
for i in test_list:
if i[ 1 ] not in x:
x.append(i[ 1 ])
for i in x:
p = []
for j in test_list:
if j[ 1 ] = = i:
p.append(j[ 0 ])
res[i] = p
print ( "Grouped Dictionary : " + str (res))
|
Output
The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Grouped Dictionary : {5: [6, 2], 7: [2, 8, 3], 8: [9]}
Time complexity: O(n^2)
Auxiliary space: O(n)
Method #4: Using defaultdict
Use the defaultdict from the collections module to group the first elements by the second elements in a tuple list.
Step-by-step approach:
- Import the defaultdict class from the collections module.
- Initialize a defaultdict with a list as the default value.
- Loop through each tuple in the input list, and append the first element of the tuple to the list associated with the second element of the tuple in the defaultdict.
- Return the resulting defaultdict as a regular dictionary.
Below is the implementation of the above approach:
Python3
from collections import defaultdict
test_list = [( 6 , 5 ), ( 2 , 7 ), ( 2 , 5 ), ( 8 , 7 ), ( 9 , 8 ), ( 3 , 7 )]
print ( "The original list is : " + str (test_list))
res = defaultdict( list )
for key, val in test_list:
res[val].append(key)
res = dict (res)
print ( "Grouped Dictionary : " + str (res))
|
Output
The original list is : [(6, 5), (2, 7), (2, 5), (8, 7), (9, 8), (3, 7)]
Grouped Dictionary : {5: [6, 2], 7: [2, 8, 3], 8: [9]}
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), to store the defaultdict.
Method #6: Using pandas
Use pandas to group the tuples by their second element and get the corresponding first elements as a list.
Step-by-step approach:
- Import the pandas library.
- Convert the list of tuples to a pandas DataFrame.
- Set the second element of each tuple as the index of the DataFrame.
- Group the DataFrame by the index and aggregate the first elements of each tuple into a list.
- Convert the resulting pandas Series back to a dictionary.
- Print the resulting grouped dictionary.
Below is the implementation of the above approach:
Python3
import pandas as pd
test_list = [( 6 , 5 ), ( 2 , 7 ), ( 2 , 5 ), ( 8 , 7 ), ( 9 , 8 ), ( 3 , 7 )]
df = pd.DataFrame(test_list, columns = [ 'first' , 'second' ])
grouped = df.groupby( 'second' )[ 'first' ].agg( list )
grouped_dict = grouped.to_dict()
print ( "Grouped Dictionary : " + str (grouped_dict))
|
Output:
Grouped Dictionary : {5: [6, 2], 7: [2, 8, 3], 8: [9]}
Time complexity: O(n log n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Similar Reads
Python - Sort by Frequency of second element in Tuple List
Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_l
6 min read
Python | Binary Group Tuple list elements
Sometimes, while working with tuples, we can have problems of grouping them, be it based on gender or any particular binary category. This can have applications in many domains. Let's discuss certain ways in which this can be performed. Method #1 : Using generator + loop + zip() The brute force meth
4 min read
Removing Tuples from a List by First Element Value - Python
In this problem we need to delete tuples based on a specific condition related to their first element. For example: We are given the list data = [("GeeksforGeeks", "Python", 1000), ("CodingForAll", "Java", 1200)] and we need to remove all tuples where the first element is "GeeksforGeeks", the desire
3 min read
Python - Filter Tuples by Kth element from List
Given a list of tuples, filter by Kth element presence in List. Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 2 Output : [('is', 4, 3)] Explanation : 3 is 2nd element and present in list, hence filtered tuple. Input : test_list = [("GFg", 5, 9),
5 min read
Python - Add list elements to tuples list
Sometimes, while working with Python tuples, we can have a problem in which we need to add all the elements of a particular list to all tuples of a list. This kind of problem can come in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be don
6 min read
Python - Group Tuples by Kth Index Element
Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of elements of tuple by similar Kth index element. This kind of problem can have application in web development domain. Let's discuss the certain way in which this task can be performed. Input :
5 min read
Get first element from a List of tuples - Python
The goal here is to extract the first element from each tuple in a list of tuples. For example, given a list [(1, 'sravan'), (2, 'ojaswi'), (3, 'bobby')], we want to retrieve [1, 2, 3], which represents the first element of each tuple. There are several ways to achieve this, each varying in terms of
2 min read
Python - Get Nth column elements in Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
8 min read
Python | Sort tuple based on occurrence of first element
Given a list of tuples, write a Python program to sort the list based on the occurrence of first element of tuples. Examples: Input : [(1, 'Jake'), (2, 'Bob'), (1, 'Cara')] Output : [(1, 'Jake', 'Cara', 2), (2, 'Bob', 1)] Input : [('b', 'ball'), ('a', 'arm'), ('b', 'b'), ('a', 'ant')] Output : [('a'
2 min read
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 C/C++ Code # Python code to find common #
7 min read