Open In App

Python – Group Similar items to Dictionary Values List

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of elements, perform grouping of similar elements, as different key-value lists in a dictionary.

Input : test_list = [4, 6, 6, 4, 2, 2, 4, 8, 5, 8] 
Output : {4: [4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]} 
Explanation : Similar items grouped together on occurrences. 

Input : test_list = [7, 7, 7, 7] 
Output : {7 : [7, 7, 7, 7]} 
Explanation : Similar items grouped together on occurrences.

Method #1 : Using defaultdict() + loop

This is one of the ways in which this task can be performed. In this, we construct a defaultdict() with a default list and keep appending similar values into a similar list.

Step-by-step approach:

  1. Import the defaultdict class from the collections module.
  2. Create a list called test_list containing several integers.
  3. Print the original list.
  4. Create an empty dictionary using the defaultdict class and assign it to a variable called res.
  5. Loop through each element in the test_list.
    1. Append the current element to the list in the res dictionary corresponding to its value.
  6. Print the resulting dictionary, which contains groups of similar items as values.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Group Similar items to Dictionary Values List
# Using defaultdict + loop
from collections import defaultdict
 
# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
 
# printing original list
print("The original list : " + str(test_list))
 
# using defaultdict for default list
res = defaultdict(list)
for ele in test_list:
     
    # appending Similar values
    res[ele].append(ele)
 
# printing result
print("Similar grouped dictionary : " + str(dict(res)))


Output

The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Similar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #2 : Using dictionary comprehension + Counter()

This is yet another way in which this task can be performed. In this, we extract frequency using Counter() and then repeat occurrences using multiplication.

Python3




# Python3 code to demonstrate working of
# Group Similar items to Dictionary Values List
# Using dictionary comprehension + Counter()
from collections import Counter
 
# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
 
# printing original list
print("The original list : " + str(test_list))
 
# using * operator to perform multiplication
res = {key : [key] * val for key, val in Counter(test_list).items()}
 
# printing result
print("Similar grouped dictionary : " + str(res))


Output

The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Similar grouped dictionary : {4: [4, 4, 4, 4], 6: [6, 6], 2: [2, 2], 8: [8, 8], 5: [5]}

Time Complexity: O(n) where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list 

Method #3: Using set() and list comprehension

 In this method, we first use the set() function to get the unique elements in the list. We then create a dictionary with empty lists as values using a dictionary comprehension. Finally, we use a list comprehension to iterate through the input list and append each item to the corresponding list in the dictionary.

Python3




# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
 
# printing original list
print("The original list : " + str(test_list))
 
# using set() to get unique elements in list
unique_items = set(test_list)
 
# creating dictionary with empty lists as values
res = {key: [] for key in unique_items}
 
# using list comprehension to group similar items
[res[item].append(item) for item in test_list]
 
# printing result
print("Similar grouped dictionary : " + str(res))


Output

The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Similar grouped dictionary : {2: [2, 2], 4: [4, 4, 4, 4], 5: [5], 6: [6, 6], 8: [8, 8]}

Time complexity: O(n) because we are using a set() to get the unique elements in the list, which takes O(n) time. Creating the dictionary with empty lists as values using dictionary comprehension takes O(m) time, where m is the number of unique elements in the list.
Auxiliary space: O(m + n) because we are creating a dictionary with m keys and empty lists as values, and also creating a set() with n elements.

Method 4: Using the groupby function from the itertools module. 

Step-by-step approach:

  • Import the itertools module.
  • Sort the original list.
  • Use the groupby function to group similar items.
  • Create a dictionary with the groups as keys and the items in the group as values.
  • Print the resulting dictionary.

Below is the implementation of the above approach:

Python3




# Step 1
import itertools
 
# initializing list
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
 
# Step 2
test_list.sort()
 
# Step 3
groups = itertools.groupby(test_list)
 
# Step 4
res = {k: list(v) for k, v in groups}
 
# Step 5
print("Similar grouped dictionary : " + str(res))


Output

Similar grouped dictionary : {2: [2, 2], 4: [4, 4, 4, 4], 5: [5], 6: [6, 6], 8: [8, 8]}

Time complexity: O(n log n) due to the sorting operation.
Auxiliary space: O(n) for storing the dictionary.

Method 5: Using the itertools.zip_longest function

  1. Import the itertools module.
  2. Sort the given list test_list.
  3. Use the zip_longest() function from the itertools module to group the consecutive identical elements in the sorted list into tuples.
  4. Convert the tuples into lists.
  5. Create a dictionary with the lists as values and the first element of each tuple as the key.
  6. Print the resulting dictionary.

Python3




import itertools
 
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
 
test_list.sort()
 
grouped_lists = [list(g) for k, g in itertools.groupby(test_list)]
 
res_dict = {lst[0]: lst for lst in grouped_lists}
 
print("Similar grouped dictionary: ", res_dict)


Output

Similar grouped dictionary:  {2: [2, 2], 4: [4, 4, 4, 4], 5: [5], 6: [6, 6], 8: [8, 8]}

Time complexity: O(N log(N)) due to the sorting of the list.
Auxiliary space: O(N) for the resulting dictionary.

Method 6: Using a while loop and a temporary list

Step-by-step approach:

  • Sort the given list in ascending order
  • Initialize an empty dictionary ‘res’
  • Initialize an empty list ‘temp’
  • Initialize a variable ‘prev’ with None
  • Use a while loop to iterate through the sorted list
    • If the current element is equal to ‘prev’ or if ‘prev’ is None, append the current element to ‘temp’
    • If the current element is not equal to ‘prev’, add the current ‘temp’ list to the ‘res’ dictionary with ‘prev’ as key
    • Update the value of ‘prev’ to the current element
  • After the loop, add the last ‘temp’ list to the ‘res’ dictionary with the last element of the list as key
  • Print the ‘res’ dictionary

Below is the implementation of the above approach:

Python3




test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
test_list.sort()
res = {}
temp = []
prev = None
 
while test_list:
    curr = test_list.pop(0)
    if curr == prev or prev is None:
        temp.append(curr)
    else:
        res[prev] = temp
        temp = [curr]
    prev = curr
 
res[prev] = temp
print("Similar grouped dictionary : " + str(res))


Output

Similar grouped dictionary : {2: [2, 2], 4: [4, 4, 4, 4], 5: [5], 6: [6, 6], 8: [8, 8]}

Time Complexity: O(nlogn) for sorting the list and O(n) for iterating through the list
Auxiliary Space: O(n)



Next Article

Similar Reads

Python program to group keys with similar values in a dictionary
Given a dictionary with values as a list. Group all the keys together with similar values. Input : test_dict = {"Gfg": [5, 6], "is": [8, 6, 9], "best": [10, 9], "for": [5, 2], "geeks": [19]} Output : [['Gfg', 'is', 'for'], ['is', 'Gfg', 'best'], ['best', 'is'], ['for', 'Gfg']] Explanation : Gfg has 6, is has 6, and for has 5 which is also in Gfg he
2 min read
Python - Group similar value list to dictionary
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 co
6 min read
Python - Group Similar keys in dictionary
Sometimes while working with dictionary data, we can have problems in which we need to perform grouping based on the substring of keys and reform the data grouped on similar keys. This can have application in data preprocessing. Let us discuss certain ways in which this task can be performed. Method #1: Using loop This is brute way in which we perf
5 min read
Python - Pairs with multiple similar values in dictionary
Sometimes, while working with dictionaries, we can have a problem in which we need to keep the dictionaries which are having similar key's value in other dictionary. This is a very specific problem. This can have applications in web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehensi
4 min read
Python - Convert dictionary items to values
Sometimes, while working with Python dictionary, we can have a problem in which we need to convert all the items of dictionary to a separate value dictionary. This problem can occur in applications in which we receive dictionary in which both keys and values need to be mapped as separate values. Let's discuss certain ways in which this task can be
3 min read
Python program to extract dictionary items for custom values
Given a dictionary, extract all the items that match given values in the list Example: Input : test_dict = {"Gfg" : 3, "is" : 5, "for" : 8, "Geeks" : 10, "Best" : 16 }, sub_list = [5, 4, 10, 20, 16, 8] Output : {'is': 5, 'Geeks': 10, 'Best': 16, "for" : 8} Explanation : All values matching list values extracted along with keys. Input : test_dict =
4 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python - Create nested list containing values as the count of list items
Given a list, the task is to write a Python program to create a nested list where the values are the count of list items. Examples: Input: [1, 2, 3] Output: [[1], [2, 2], [3, 3, 3]] Input: [4, 5] Output: [[1, 1, 1, 1], [2, 2, 2, 2, 2]] Method 1: Using nested list comprehension The list will contain the count of the list items for each element e in
2 min read
Python Program to find the profit or loss when CP of N items is equal to SP of M items
Given [Tex]N   [/Tex]and [Tex]M   [/Tex]denoting that the Cost Price of N articles is equal to the Selling Price of M articles. The task is to determine the profit or Loss percentage. Examples:  Input: N = 8, M = 9 Output: Loss = -11.11% Input: N = 8, M = 5 Output: Profit = 60% Formula:-  Below is the implementation of the above approach: C/C++ Cod
1 min read
Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or
5 min read
three90RightbarBannerImg