Home > OS >  Grouping keys and values with Python
Grouping keys and values with Python

Time:05-15

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.

CodePudding user response:

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))
]

CodePudding user response:

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)]
  • Related