Open In App

Python – Group elements from Dual List Matrix

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 code to demonstrate
# Group elements from Dual List Matrix
# using loop + list comprehension
 
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Group elements from Dual List Matrix
# using loop + list comprehension
res = {key: [] for key in test_list1}
for key in res:
    res[key] = [sub[1] for sub in test_list2 if key == sub[0]]
             
# printing result
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 code to demonstrate
# Group elements from Dual List Matrix
# using dictionary comprehension
 
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Group elements from Dual List Matrix
# using dictionary comprehension
res = {key: [sub[1] for sub in test_list2 if key == sub[0]] for key in test_list1}
             
# printing result
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 code to demonstrate
# Group elements from Dual List Matrix
 
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Group elements from Dual List Matrix
res=dict()
for i in test_list1:
    x=[]
    for j in test_list2:
        if i in j:
            x.append(j[1])
    res[i]=x
         
     
# printing result
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

  1. Import the defaultdict from the collections module.
  2. Initialize two lists test_list1 and test_list2.
  3. Print the original lists using the print() function.
  4. Create an empty defaultdict named ‘res’ using the defaultdict() function.
  5. Use a for loop to iterate over the elements of test_list2.
  6. 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.
  7. 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.
  8. Convert the defaultdict to a regular dictionary using the dict() function.
  9. Print the resulting dictionary using the print() function.




from collections import defaultdict
 
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Group elements from Dual List Matrix
res = defaultdict(list)
for i, j in test_list2:
    res[i].append(j)
 
# Convert the defaultdict to a regular dictionary
res = dict(res)
 
# printing result
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
 
# Initializing lists
test_list1 = ['Gfg', 'is', 'best']
test_list2 = [['Gfg', 1], ['is', 2], ['best', 1], ['Gfg', 4], ['is', 8], ['Gfg', 7]]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Group elements from Dual List Matrix
test_list2.sort()
res = {}
for key, group in itertools.groupby(test_list2, lambda x: x[0]):
    res[key] = [val[1] for val in group]
 
# printing result
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)


Article Tags :