Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Grouped summation of tuple list in Python
When working with lists of tuples representing key-value pairs, you often need to group them by keys and sum their values. Python's Counter from the collections module provides an elegant solution for this task.
The Counter is a specialized dictionary subclass that counts hashable objects. It creates a hash table automatically when initialized with an iterable, making it perfect for aggregating values by keys.
Using Counter for Grouped Summation
Here's how to sum values for matching keys across multiple tuple lists ?
from collections import Counter
my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)]
my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)]
print("The first list is:")
print(my_list_1)
print("The second list is:")
print(my_list_2)
# Convert tuple lists to Counter objects
cumulative_val_1 = Counter(dict(my_list_1))
cumulative_val_2 = Counter(dict(my_list_2))
# Add counters to sum values for matching keys
cumulative_val_3 = cumulative_val_1 + cumulative_val_2
my_result = list(cumulative_val_3.items())
print("The grouped summation of list of tuple is:")
print(my_result)
The first list is:
[('Hi', 14), ('there', 16), ('Jane', 28)]
The second list is:
[('Jane', 12), ('Hi', 4), ('there', 21)]
The grouped summation of list of tuple is:
[('Hi', 18), ('there', 37), ('Jane', 40)]
Alternative Approach Using defaultdict
You can also use defaultdict for more control over the summation process ?
from collections import defaultdict
my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)]
my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)]
# Create defaultdict with int as default factory
result_dict = defaultdict(int)
# Sum values for all tuple lists
for key, value in my_list_1 + my_list_2:
result_dict[key] += value
my_result = list(result_dict.items())
print("Grouped summation using defaultdict:")
print(my_result)
Grouped summation using defaultdict:
[('Hi', 18), ('there', 37), ('Jane', 40)]
How It Works
The process involves these key steps:
- Convert to dictionaries: Tuple lists become key-value mappings
- Create Counter objects: Enable arithmetic operations on dictionaries
-
Add Counters: The
+operator sums values for matching keys -
Extract results: Convert back to list of tuples using
items()
Comparison
| Method | Code Complexity | Performance | Best For |
|---|---|---|---|
Counter |
Simple | Good | Multiple lists |
defaultdict |
Medium | Better | Large datasets |
Conclusion
Use Counter for simple grouped summation of tuple lists as it provides clean, readable code. For better performance with large datasets, consider defaultdict with manual iteration.
