I have a list of lists that contain dictionaries.
users = [[{'USERID': 302154, 'SALARY': 130.645, 'EXPERIENCE': 9},
{'USERID': 506005, 'SALARY': 140.137, 'EXPERIENCE': 3}],
[{'USERID': 302154, 'SALARY': 121.0, 'EXPERIENCE': 9},
{'USERID': 506005, 'SALARY': 57.987, 'EXPERIENCE': 3}]
]
I want to get one dictionary for each user and summarize the "Salary" by "UserID":
result = [{'USERID': 302154, 'SALARY': 251.645, 'EXPERIENCE': 9},
{'USERID': 506005, 'SALARY': 198.124, 'EXPERIENCE': 3}]
How do I implement this?
>Solution :
You can use itertools.chain to flatten the list and simply iterate and add the SALARY using a dictionary as intermediate container:
from itertools import chain
out = {}
for d in chain.from_iterable(users):
if d['USERID'] in out:
out[d['USERID']]['SALARY'] += d['SALARY']
else:
out[d['USERID']] = d.copy() # making a copy to avoid modifying original
out = list(out.values())
output:
[{'USERID': 302154, 'SALARY': 251.645, 'EXPERIENCE': 9},
{'USERID': 506005, 'SALARY': 198.124, 'EXPERIENCE': 3}]