Open In App
Related Articles

Python – Group similar value list to dictionary

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Sometimes, while working with Python list, we can have a problem in which we need to group similar value lists indices to values into a dictionary. This can have a good application in domains in which we need grouped dictionary as output for pair of lists. Lets discuss certain ways in which this task can be performed. 

Method #1: Using dictionary comprehension This is way in which this task can be performed. In this, we iterate one list along with other and keep constructing dictionary with similar key from one list and corresponding values from other. This is one liner solution. 

Python3

# Python3 code to demonstrate
# Group similar value list to dictionary
# using dictionary comprehension
 
# Initializing lists
test_list1 = [4, 4, 4, 5, 5, 6, 6, 6, 6]
test_list2 = ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
 
# Printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Group similar value list to dictionary
# using dictionary comprehension
res = {key : [test_list2[idx]
      for idx in range(len(test_list2)) if test_list1[idx]== key]
      for key in set(test_list1)}
 
# printing result
print ("Mapped resultant dictionary : " + str(res))

                    

Output
The original list 1 is : [4, 4, 4, 5, 5, 6, 6, 6, 6]
The original list 2 is : ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
Mapped resultant dictionary : {4: ['G', 'f', 'g'], 5: ['i', 's'], 6: ['b', 'e', 's', 't']}

Time Complexity: O(n*n)
Auxiliary Space: O(n)

Method #2 : Using defaultdict() + loop This is yet another way in which this task can be performed. In this we avoid testing for keys presence in dictionary by creating a defaultdict(). 

Python3

# Python3 code to demonstrate
# Group similar value list to dictionary
# using defaultdict() + loop
from collections import defaultdict
 
# Initializing lists
test_list1 = [4, 4, 4, 5, 5, 6, 6, 6, 6]
test_list2 = ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Group similar value list to dictionary
# using defaultdict() + loop
res = defaultdict(set)
for key, val in zip(test_list1, test_list2):
    res[key].add(val)
res = {key: list(val) for key, val in res.items()}
 
# printing result
print ("Mapped resultant dictionary : " + str(res))

                    

Output
The original list 1 is : [4, 4, 4, 5, 5, 6, 6, 6, 6]
The original list 2 is : ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
Mapped resultant dictionary : {4: ['g', 'G', 'f'], 5: ['s', 'i'], 6: ['t', 's', 'b', 'e']}

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.

Method #3 : Using for loop,list() and set() methods

Step-by-step approach:

  • A dictionary res is initialized to store the grouped values. An empty list a is also initialized to hold the values of test_list2 corresponding to the current key of test_list1.
  • The list(set(test_list1)) line creates a list x containing only the unique values from test_list1.
  • The program then iterates over each unique value in x using a for loop.
  • For each unique value in x, the program creates an empty list a to store the corresponding values from test_list2.
    • Iterates over each value in test_list1 using another for loop.
      • If the current value of test_list1 is equal to the current unique value from x, the corresponding value from test_list2 is appended to list a.
      • Once all values from test_list1 have been checked, list a is added to the dictionary res with the current unique value from x as the key.
      • Once all unique values in x have been processed, the resulting dictionary res is printed using the print() function.
  • Overall, uses nested loops to iterate over the input lists and group similar values from test_list1 into a dictionary where the keys are the unique values from test_list1 and the values are the corresponding values from test_list2.

Below is the implementation of the above approach:

Python3

# Python3 code to demonstrate
# Group similar value list to dictionary
 
# Initializing lists
test_list1 = [4, 4, 4, 5, 5, 6, 6, 6, 6]
test_list2 = ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
 
# Printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# Group similar value list to dictionary
res = dict()
x = list(set(test_list1))
for i in x:
    a = []
    for j in range(0, len(test_list1)):
        if(i == test_list1[j]):
            a.append(test_list2[j])
    res[i] = a
 
# Printing result
print("Mapped resultant dictionary : " + str(res))

                    

Output
The original list 1 is : [4, 4, 4, 5, 5, 6, 6, 6, 6]
The original list 2 is : ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
Mapped resultant dictionary : {4: ['G', 'f', 'g'], 5: ['i', 's'], 6: ['b', 'e', 's', 't']}

Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements

Method 4: use the zip() function and dictionary comprehension.

Step-by-step approach:

  • Zip the two input lists together using zip(test_list1, test_list2) to create a list of tuples with corresponding elements from both lists.
  • Convert the zipped list into a set of tuples using set(). This will remove duplicate elements.
  • Use dictionary comprehension to create a dictionary where each key is a unique value from the first element of the tuples, and the corresponding value is a list of the second element from the tuples that have the same first element.

Below is the implementation of the above approach:

Python3

from itertools import groupby
 
test_list1 = [4, 4, 4, 5, 5, 6, 6, 6, 6]
test_list2 = ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']
 
res = {k: [v for _, v in lst] for k, lst in
       groupby(sorted(zip(test_list1, test_list2)), key=lambda x: x[0])}
 
print("Mapped resultant dictionary : " + str(res))

                    

Output
Mapped resultant dictionary : {4: ['G', 'f', 'g'], 5: ['i', 's'], 6: ['b', 'e', 's', 't']}

Time complexity: O(n log n), where n is the length of the input lists.
Auxiliary space: O(n), where n is the length of the input lists.


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.


Last Updated : 10 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials