1

I have a list of dictionaries which looks like this:

[{'success': 10, 'failed': 15, 'manual': 20},
 {'manual': 5, 'success': 10},
 {},
 {},
 {'success': 20, 'manual': 25, 'failed': 30},
 {'success': 2, 'manual': 4, 'failed': 6},
 {},
 {}]

I want to sum up the values of keys for first four dictionaries and then again sum up the values of keys for next four dictionaries which ultimately gives me finally an output of two dictionaries with summed values as below:

[{'success': 20, 'failed': 15, 'manual': 25},
 {'success': 22, 'manual': 29, 'success': 36}]

Can someone help with a way to achieve this for a dynamic list?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
bikash_sb
  • 11
  • 2
  • I was finally able to resolve it myself with this code: `initial_state = list() final_state = list() for m in range(0, len(state), 4): initial_state = dict(functools.reduce(operator.add, map(collections.Counter, state[m:m + 4]))) final_state.append(initial_state)` Any better solutions are welcome. – bikash_sb Dec 08 '22 at 18:04
  • Using Counter makes it sort the keys by value. If that's cool, your answer is good. See https://stackoverflow.com/a/312464/1766544 and https://stackoverflow.com/a/11011846/1766544 It looks a little cleaner with those and sum instead of functools and operator. I can post, but it will be very similar to what you already have. – Kenny Ostrom Dec 08 '22 at 23:47

1 Answers1

0

You could subtotal every 4 lines of data and store the results in a list as follows:

from pprint import pprint

data = [
    {'success': 10, 'failed': 15, 'manual': 20},
    {'manual': 5, 'success': 10},
    {},
    {},
    {'success': 20, 'manual': 25, 'failed': 30},
    {'success': 2, 'manual': 4, 'failed': 6},
    {},
    {}
]

subtotal = {"success": 0, "failed": 0, "manual": 0}
results = []
for count, datum in enumerate(data, 1):
    if count % 4 == 0:
        results.append(dict(subtotal))
        subtotal = {"success": 0, "failed": 0, "manual": 0}
    for key, value in datum.items():
        subtotal[key] += value
        
pprint(results)

Output:

[{'failed': 15, 'manual': 25, 'success': 20},
 {'failed': 36, 'manual': 29, 'success': 22}]
rhurwitz
  • 2,557
  • 2
  • 10
  • 18