'Grouping keys and values with Python
I have some data. numeric key and numeric value:
[
(468793398, 672),
(468793398, 2464),
(521683990, 131152)
]
I need to group keys and values like this:
[
(468793398, 3136),
(521683990, 131152)
]
The key should be unique and values with the same key should be incremented to each other.
Please help me to write a python code to solve this problem. It looks simple, but I have no idea.
Solution 1:[1]
Another solution:
lst = [(468793398, 672), (468793398, 2464), (521683990, 131152)]
out = {}
for k, v in lst:
out[k] = out.get(k, 0) + v
print(list(out.items()))
Prints:
[(468793398, 3136), (521683990, 131152)]
Solution 2:[2]
You can use itertools.groupby (and operator.itemgetter) for this:
from itertools import groupby
from operator import itemgetter
lst = [
(468793398, 672),
(468793398, 2464),
(521683990, 131152)
]
result = [
(key, sum(map(itemgetter(1), group)))
for key, group in groupby(lst, key=itemgetter(0))
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrej Kesely |
| Solution 2 | trincot |
