Home > Mobile >  Fold the values ​of two dictionaries if the definite key matches
Fold the values ​of two dictionaries if the definite key matches

Time:03-16

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?

CodePudding user response:

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}]

CodePudding user response:

result = []
for i in users: #that iterates users' list
    temp_userid = ""
    temp_salary = 0
    temp_experience = 0
    for j in i: #that iterates one user's list (iterate user's dicts)
        temp_userid = j["USERID"]
        temp_salary  = j["SALARY"]
        temp_experience = j["EXPERIENCE"]

    temp_dict = {}
    temp_dict["USERID"] = temp_userid
    temp_dict["SALARY"] = temp_salary
    temp_dict["EXPERIENCE"] = temp_experience
    
    results.append(temp_dict)

#result array is hopefully what you want.
#I've not run it, neither is the fastest way
#of doing that, yet it provides some intuition.
  • Related