Python | Aggregate values by tuple keys
Last Updated :
07 May, 2023
Sometimes, while working with records, we can have a problem in which we need to group the like keys and aggregate the values of like keys. This can have application in any kind of scoring. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using Counter() + generator expression The combination of above functions can be used to perform this particular task. In this, we need to first combine the like key elements and task of aggregation is performed by Counter().
Python3
from collections import Counter
test_list = [( 'gfg' , 50 ), ( 'is' , 30 ), ( 'best' , 100 ),
( 'gfg' , 20 ), ( 'best' , 50 )]
print ("The original list is : " + str (test_list))
res = list (Counter(key for key, num in test_list
for idx in range (num)).items())
print (" List after grouping : " + str (res))
|
Output :
The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)]
List after grouping : [('best', 150), ('gfg', 70), ('is', 30)]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. Counter() + generator expression performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #2 : Using groupby() + map() + itemgetter() + sum() The combination of above functions can also be used to perform this particular task. In this, we group the elements using groupby(), decision of key’s index is given by itemgetter. Task of addition(aggregation) is performed by sum() and extension of logic to all tuples is handled by map().
Python3
from itertools import groupby
from operator import itemgetter
test_list = [( 'gfg' , 50 ), ( 'is' , 30 ), ( 'best' , 100 ),
( 'gfg' , 20 ), ( 'best' , 50 )]
print ("The original list is : " + str (test_list))
res = [(key, sum ( map (itemgetter( 1 ), ele)))
for key, ele in groupby( sorted (test_list, key = itemgetter( 0 )),
key = itemgetter( 0 ))]
print (" List after grouping : " + str (res))
|
Output :
The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)]
List after grouping : [('best', 150), ('gfg', 70), ('is', 30)]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3: Using reduce():
Algorithm:
- Import the required modules, functools, itertools and operator.
- Initialize the given list of tuples.
- Use the reduce function to iterate through the list of tuples, filtering the tuples with the same first element and summing their second element.
- Append the tuples obtained from step 3 to the accumulator list, if the first element of the tuple is not
- present in the accumulator list, otherwise return the accumulator list unchanged.
- Finally, print the list after grouping.
Python3
from functools import reduce
from itertools import groupby
from operator import itemgetter
test_list = [( 'gfg' , 50 ), ( 'is' , 30 ), ( 'best' , 100 ),
( 'gfg' , 20 ), ( 'best' , 50 )]
print ( "The original list is : " + str (test_list))
res = reduce ( lambda acc, x: acc + [(x[ 0 ],
sum ( map (itemgetter( 1 ), filter ( lambda y: y[ 0 ] = =
x[ 0 ], test_list))))] if x[ 0 ] not in [elem[ 0 ] for elem in acc]
else acc, test_list, [])
print ( "List after grouping : " + str (res))
|
Output
The original list is : [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)]
List after grouping : [('gfg', 70), ('is', 30), ('best', 150)]
Time Complexity: O(nlogn), where n is the length of the input list. This is due to the sorting operation performed by the groupby function.
Auxiliary Space: O(n), where n is the length of the input list. This is due to the list created by the reduce function to store the output tuples.
METHOD 4:Using dictionary.
APPROACH:
The program takes a list of tuples as input and aggregates the values by the tuple keys. In other words, it groups the values of tuples with the same key and sums their values.
ALGORITHM:
1.Initialize an empty dictionary d.
2.Loop through each tuple in the list:
a.Check if the key of the tuple is already present in the dictionary.
b.If the key is present, add the value of the tuple to the existing value of the key in the dictionary.
c.If the key is not present, add the key-value pair to the dictionary.
5.Convert the dictionary to a list of tuples using the items() method.
6.Print the list.
Python3
lst = [( 'gfg' , 50 ), ( 'is' , 30 ), ( 'best' , 100 ), ( 'gfg' , 20 ), ( 'best' , 50 )]
d = {}
for key, value in lst:
if key in d:
d[key] + = value
else :
d[key] = value
result = list (d.items())
print ( "List after grouping :" , result)
|
Output
List after grouping : [('gfg', 70), ('is', 30), ('best', 150)]
Time Complexity:
The time complexity of this program is O(n), where n is the length of the input list.
Space Complexity:
The space complexity of this program is O(m), where m is the number of unique keys in the input list. This is because the program creates a dictionary to store the keys and their corresponding values.
Similar Reads
Get specific keys' values - Python
Our task is to retrieve values associated with specific keys from a dictionary. This is especially useful when we only need to access certain pieces of data rather than the entire dictionary. For example, suppose we have the following dictionary: d = {'name': 'John', 'age': 25, 'location': 'New York
3 min read
Python - Keys Values equal frequency
Given a dictionary, count instances where keys are equal to values. Input : test_dict = {5:5, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 2 Explanation : At 2 instances, keys are equal to values.Input : test_dict = {5:4, 8:9, 7:8, 1:2, 10:10, 4:8} Output : 1 Explanation : At 1 instance, key is equal to valu
4 min read
Python - Group keys to values list
Sometimes, while working with Python dictionaries, we can have problem in which we need to find all possible values of all keys in a dictionary. This utility is quite common and can occur in many domains including day-day programming and school programming. Lets discuss certain way in which this tas
5 min read
Python - Extract Unique value key pairs
Sometimes, while working on Python dictionaries, we can have a problem in which we need to perform the extraction of selected pairs of keys from dictionary list, that too unique. This kind of problem can have application in many domains including day-day programming. Let's discuss certain ways in wh
5 min read
Iterate Through Dictionary Keys And Values In Python
In Python, a Dictionary is a data structure where the data will be in the form of key and value pairs. So, to work with dictionaries we need to know how we can iterate through the keys and values. In this article, we will explore different approaches to iterate through keys and values in a Dictionar
2 min read
Python - Extracting keys not in values
Sometimes, while working with Python dictionaries, we can have a problem in which we require to get all the keys that do not occur in values lists. This can have applications in the domains such as day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using
5 min read
Python - Create Dictionary Of Tuples
The task of creating a dictionary of tuples in Python involves mapping each key to a tuple of values, enabling structured data storage and quick lookups. For example, given a list of names like ["Bobby", "Ojaswi"] and their corresponding favorite foods as tuples [("chapathi", "roti"), ("Paraota", "I
3 min read
Python - Unique Values of Key in Dictionary
We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name" Then, the unique value
4 min read
Python - Dictionary Tuple Values Update
The task of updating tuple values in a dictionary involves modifying each tuple in the dictionary by applying a specific operation to its elements. In this case, the goal is to update each element of the tuple based on a given condition, such as multiplying each element by a constant. For example, g
3 min read
Python | Group tuple into list based on value
Sometimes, while working with Python tuples, we can have a problem in which we need to group tuple elements to nested list on basis of values allotted to it. This can be useful in many grouping applications. Let's discuss certain ways in which this task can be performed. Method #1 : Using itemgetter
6 min read