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
# Python3 code to demonstrate working of
# Aggregate values by tuple keys
# using Counter() + generator expression
from collections import Counter
# initialize list
test_list = [('gfg', 50), ('is', 30), ('best', 100),
('gfg', 20), ('best', 50)]
# printing original list
print("The original list is : " + str(test_list))
# Aggregate values by tuple keys
# using Counter() + generator expression
res = list(Counter(key for key, num in test_list
for idx in range(num)).items())
# printing result
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
# Python3 code to demonstrate working of
# Aggregate values by tuple keys
# using groupby() + map() + itemgetter() + sum()
from itertools import groupby
from operator import itemgetter
# initialize list
test_list = [('gfg', 50), ('is', 30), ('best', 100),
('gfg', 20), ('best', 50)]
# printing original list
print("The original list is : " + str(test_list))
# Aggregate values by tuple keys
# using groupby() + map() + itemgetter() + sum()
res = [(key, sum(map(itemgetter(1), ele)))
for key, ele in groupby(sorted(test_list, key = itemgetter(0)),
key = itemgetter(0))]
# printing result
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
# initialize list
test_list = [('gfg', 50), ('is', 30), ('best', 100),
('gfg', 20), ('best', 50)]
# printing original list
print("The original list is : " + str(test_list))
# use reduce() to aggregate values by tuple keys
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, [])
# printing result
print("List after grouping : " + str(res))
# This code is contributed by Jyothi pinjala.
OutputThe 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
# Input
lst = [('gfg', 50), ('is', 30), ('best', 100), ('gfg', 20), ('best', 50)]
# Aggregate values using a dictionary
d = {}
for key, value in lst:
if key in d:
d[key] += value
else:
d[key] = value
# Convert dictionary to list of tuples
result = list(d.items())
# Output
print("List after grouping :", result)
OutputList 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
Python - Tuple key detection from value list Sometimes, while working with record data, we can have a problem in which we need to extract the key which has matching value of K from its value list. This kind of problem can occur in domains that are linked to data. Lets discuss certain ways in which this task can be performed. Method #1 : Using
6 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 - Merge keys by values Given a dictionary, merge the keys to map to common values. Examples: Input : test_dict = {1:6, 8:1, 9:3, 10:3, 12:6, 4:9, 2:3} Output : {'1-12': 6, '2-9-10': 3, '4': 9, '8': 1} Explanation : All the similar valued keys merged.Input : test_dict = {1:6, 8:1, 9:3, 4:9, 2:3} Output : {'1': 6, '2-9': 3,
7 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
Create Dictionary Of Tuples - Python 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 | Filter Tuple Dictionary Keys Sometimes, while working with Python dictionaries, we can have itâs keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functi
4 min read
Python - Summation of tuple dictionary values Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Letâs discuss certain ways in which this particular problem can be solved. Method #1: Using
4 min read
Python | Ways to concatenate tuples Many times, while working with records, we can have a problem in which we need to add two records and store them together. This requires concatenation. As tuples are immutable, this task becomes little complex. Let's discuss certain ways in which this task can be performed. Method #1 : Using + opera
6 min read
Python - Minimum in tuple list value Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the minimum of list as tuple attribute. Letâs discuss certai
5 min read
Python | Compare tuples Sometimes, while working with records, we can have a problem in which we need to check if each element of one tuple is greater/smaller than it's corresponding index in other tuple. This can have many possible applications. Let's discuss certain ways in which this task can be performed. Method #1 : U
4 min read