M.Izzat M.Izzat - 6 months ago 49
Python Question

Calculate sum of value in python list based of employee name field

Greeting everyone, I have a list in my python file, based from this list how can I calculate sum of the

actual_duration
for each of the employee A, B and C?

Below is my list :

[{'employee_name': 'A', 'actual_duration': 14},
{'employee_name': 'A', 'actual_duration': 6},
{'employee_name': 'B', 'actual_duration': 8},
{'employee_name': 'B', 'actual_duration': 22},
{'employee_name': 'C', 'actual_duration': 15}]

Answer Source

One way is using collections.defaultdict

l = [   {'employee_name': 'A', 'actual_duration': 14}, 
        {'employee_name': 'A', 'actual_duration': 6}, 
        {'employee_name': 'B', 'actual_duration': 8}, 
        {'employee_name': 'B', 'actual_duration': 22}, 
        {'employee_name': 'C', 'actual_duration': 15}  ]

from collections import defaultdict
d_dict = defaultdict(int)

for k,v in [d.values() for d in l]:
    d_dict[k]+=v

new_l = []
for k,v in d_dict.items():
    new_l.append({'employee_name': k, 'actual_duration': v})

new_l

Output:

[{'actual_duration': 20, 'employee_name': 'A'},
 {'actual_duration': 30, 'employee_name': 'B'},
 {'actual_duration': 15, 'employee_name': 'C'}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download