Somanath Patil Somanath Patil - 20 days ago 6
Python Question

how to aggregate list values by sum of each elem

I have two lists

people_ids = ['123','456','123','567']

no_of_steps = [15,16,10,15]

Desired Result:

person 123 has taken 25(15+10) steps

person 456 has taken 16 steps

person 567 has taken 15 steps.


i was able to achieve it by Pandas Group by function. Can anybody suggest the Python code with out any modules?

Thanks in Advance :)

Answer

You can use a collections.defaultdict():

from collections import defaultdict

d = defaultdict(int)
for j, id in enumerate(people_ids):
    d[id] += no_of_steps[j]

# defaultdict(int, {'123': 25, '456': 16, '567': 15})