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
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 - 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 - 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
Python | Max/Min of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the min/max of tuple elements that are received as values of dictionary. We may have a problem to get index wise min/max. Let's discuss certain ways in which this particular problem can be solved. Method #1 : Using tu
5 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Python - K length Concatenate Single Valued Tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform concatenation of single values tuples, to make them into groups of a bigger size. This kind of problem can occur in web development and day-day programming. Let's discuss certain ways in which this task ca
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 | 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