Python – Group elements from Dual List Matrix
Last Updated :
02 May, 2023
Sometimes, while working with Python list, we can have a problem in which we need to group the elements in list with the first element of Matrix and perform the Grouping in form of dictionary. This can have advantage in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + list comprehension The combination of above methods can be used in performing this task. In this, we iterate through the dual element row and compute the dictionary with mapping of elements from list and 2nd column of dual row matrix.
Python3
test_list1 = [ 'Gfg' , 'is' , 'best' ]
test_list2 = [[ 'Gfg' , 1 ], [ 'is' , 2 ], [ 'best' , 1 ], [ 'Gfg' , 4 ], [ 'is' , 8 ], [ 'Gfg' , 7 ]]
print ("The original list 1 is : " + str (test_list1))
print ("The original list 2 is : " + str (test_list2))
res = {key: [] for key in test_list1}
for key in res:
res[key] = [sub[ 1 ] for sub in test_list2 if key = = sub[ 0 ]]
print ("The dictionary after grouping : " + str (res))
|
Output :
The original list 1 is : [‘Gfg’, ‘is’, ‘best’] The original list 2 is : [[‘Gfg’, 1], [‘is’, 2], [‘best’, 1], [‘Gfg’, 4], [‘is’, 8], [‘Gfg’, 7]] The dictionary after grouping : {‘is’: [2, 8], ‘Gfg’: [1, 4, 7], ‘best’: [1]}
Time complexity: O(n^2), where n is the length of test_list2.
Auxiliary space: O(n), where n is the length of test_list2.
Method #2 : Using dictionary comprehension This is yet another way in which this task can be performed. In this, we compile the logic performed above into one single dictionary comprehension for better readability.
Python3
test_list1 = [ 'Gfg' , 'is' , 'best' ]
test_list2 = [[ 'Gfg' , 1 ], [ 'is' , 2 ], [ 'best' , 1 ], [ 'Gfg' , 4 ], [ 'is' , 8 ], [ 'Gfg' , 7 ]]
print ("The original list 1 is : " + str (test_list1))
print ("The original list 2 is : " + str (test_list2))
res = {key: [sub[ 1 ] for sub in test_list2 if key = = sub[ 0 ]] for key in test_list1}
print ("The dictionary after grouping : " + str (res))
|
Output :
The original list 1 is : [‘Gfg’, ‘is’, ‘best’] The original list 2 is : [[‘Gfg’, 1], [‘is’, 2], [‘best’, 1], [‘Gfg’, 4], [‘is’, 8], [‘Gfg’, 7]] The dictionary after grouping : {‘is’: [2, 8], ‘Gfg’: [1, 4, 7], ‘best’: [1]}
Time complexity: O(n^2) where n is the length of test_list2 as we have nested loops to iterate over each element in the list.
Auxiliary space: O(n) where n is the length of test_list2 as we are creating a dictionary with keys from test_list1 and values from test_list2.
Method #3 : Using for loops
Python3
test_list1 = [ 'Gfg' , 'is' , 'best' ]
test_list2 = [[ 'Gfg' , 1 ], [ 'is' , 2 ], [ 'best' , 1 ], [ 'Gfg' , 4 ], [ 'is' , 8 ], [ 'Gfg' , 7 ]]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = dict ()
for i in test_list1:
x = []
for j in test_list2:
if i in j:
x.append(j[ 1 ])
res[i] = x
print ( "The dictionary after grouping : " + str (res))
|
Output
The original list 1 is : ['Gfg', 'is', 'best']
The original list 2 is : [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
The dictionary after grouping : {'Gfg': [1, 4, 7], 'is': [2, 8], 'best': [1]}
Time Complexity : O(N*N)
Auxiliary Space : O(N)
Method #4: Using defaultdict from the collections module
- Import the defaultdict from the collections module.
- Initialize two lists test_list1 and test_list2.
- Print the original lists using the print() function.
- Create an empty defaultdict named ‘res’ using the defaultdict() function.
- Use a for loop to iterate over the elements of test_list2.
- For each element of test_list2, extract the first and second elements of the inner list using tuple unpacking. The first element is stored in the variable i and the second element is stored in the variable j.
- Append the value of j to the list associated with the key i in the dictionary res. This is done using the append() method of the defaultdict.
- Convert the defaultdict to a regular dictionary using the dict() function.
- Print the resulting dictionary using the print() function.
Python3
from collections import defaultdict
test_list1 = [ 'Gfg' , 'is' , 'best' ]
test_list2 = [[ 'Gfg' , 1 ], [ 'is' , 2 ], [ 'best' , 1 ], [ 'Gfg' , 4 ], [ 'is' , 8 ], [ 'Gfg' , 7 ]]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = defaultdict( list )
for i, j in test_list2:
res[i].append(j)
res = dict (res)
print ( "The dictionary after grouping : " + str (res))
|
Output
The original list 1 is : ['Gfg', 'is', 'best']
The original list 2 is : [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
The dictionary after grouping : {'Gfg': [1, 4, 7], 'is': [2, 8], 'best': [1]}
Time complexity: O(n), where n is the number of elements in test_list2.
Auxiliary space: O(n), to store the defaultdict.
Method #5: Using itertools.groupby()
- Import itertools module
- Sort the list by the first element of each sublist (test_list2)
- Use itertools.groupby() to group the elements by the first element of each sublist
- Convert the grouped elements into a dictionary
Python3
import itertools
test_list1 = [ 'Gfg' , 'is' , 'best' ]
test_list2 = [[ 'Gfg' , 1 ], [ 'is' , 2 ], [ 'best' , 1 ], [ 'Gfg' , 4 ], [ 'is' , 8 ], [ 'Gfg' , 7 ]]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
test_list2.sort()
res = {}
for key, group in itertools.groupby(test_list2, lambda x: x[ 0 ]):
res[key] = [val[ 1 ] for val in group]
print ( "The dictionary after grouping : " + str (res))
|
Output
The original list 1 is : ['Gfg', 'is', 'best']
The original list 2 is : [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
The dictionary after grouping : {'Gfg': [1, 4, 7], 'best': [1], 'is': [2, 8]}
Time complexity: O(nlogn) (sorting the list takes O(nlogn) time)
Auxiliary space: O(n)
Similar Reads
Python - Group Elements in Matrix
Given a Matrix with two columns, group 2nd column elements on basis of 1st column. Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]] Output : {5: [8, 4], 2: [0, 3, 9]} Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2. Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2
6 min read
Python - List Elements Grouping in Matrix
Given a Matrix, for groups according to list elements, i.e each group should contain all elements from List. Input : test_list = [[2, 6], [7, 8], [1, 4]], check_list = [1, 2, 4, 6] Output : [[7, 8], [[1, 2], [4, 6]]] Explanation : 1, 2, 4, 6 elements rows are grouped. Input : test_list = [[2, 7], [7
8 min read
Python - Group similar elements into Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are the same. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 4, 4,
8 min read
Python | Group list elements based on frequency
Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple. Examples: Input : [1, 3, 4, 4, 1, 5, 3, 1] Output : [(1, 3), (3, 2), (4, 2), (5, 1)] Input : ['x', 'a', 'x', 'y', 'a', 'x'] Output : [('x', 3), ('a', 2), ('y', 1)] Method #1: List c
5 min read
Python | Binary element list grouping
Sometimes while working with the databases, we need to perform certain list operations that are more like query language, for instance, grouping of nested list element with respect to its other index elements. This article deals with binary nested list and group each nested list element with respect
9 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
Python - Paired elements grouping
Sometimes, while working with Python records, we can have a problem in which we have tuple list as data and we desire to group all the elements which form a chain, i.e are indirect pairs of each other or are connected components. This kind of problem can occur in domains such as competitive programm
6 min read
Group Elements at Same Indices in a Multi-List - Python
We are given a 2D list, we have to group elements at the same indices in a multi-list which means combining elements that are positioned at identical indices across different list. For example:If we have a 2D list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] then grouping elements at the same indices would re
4 min read
Python - Elements frequency in Tuple Matrix
Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get the frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domains. Let's discuss certain ways in which this problem can be solved. Inp
5 min read
Python - Remove front column from Matrix
Sometimes, while working with Matrix data, we can have stray element that attached at front end of each row of matrix. This can be undesired at times and wished to be removed. Letâs discuss certain ways in which this task can be performed. Method #1: Using loop + del + list slicing The combination o
6 min read