Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fold the values ​of two dictionaries if the definite key matches

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading