Home > Blockchain >  Python: Get sum of a key value in multiple lists of dictionaries based on another key value
Python: Get sum of a key value in multiple lists of dictionaries based on another key value

Time:01-29

I have three lists:

listA = [{'fund_type_id': 1, 'fund_value': 60.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 20.0}]

ListB = [{'fund_type_id': 1, 'fund_value': 40.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 10.0}]

ListC = [{'fund_type_id': 1, 'fund_value': 20.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 30.0}]

I need to sum fund_value from listA and listC and subtract fund_value from listB for each fund_type_id (listA_fund_value - listB_fund_value listC_fund_value)

expectedList = [{'fund_type_id': 1, 'fund_value': 40.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 40.0}]

What's the most efficient and cleanest way of performing this calculation?

CodePudding user response:

This will generate what you're looking for but it is not robust as it implicitly assumes that the dictionaries are structured exactly as per your sample data:

listA = [{'fund_type_id': 1, 'fund_value': 60.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 20.0}]
listB = [{'fund_type_id': 1, 'fund_value': 40.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 10.0}]
listC = [{'fund_type_id': 1, 'fund_value': 20.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 30.0}]

el = []

for a, b, c in zip(listA, listB, listC):
    v = a['fund_value']   c['fund_value'] - b['fund_value']
    el.append({'fund_type_id': a['fund_type_id'], 'fund_value': v})

print(el)

Output:

[{'fund_type_id': 1, 'fund_value': 40.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 40.0}]

CodePudding user response:

You can use the zip() built-in and a list comprehension:

listA = [{'fund_type_id': 1, 'fund_value': 60.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 20.0}]

listB = [{'fund_type_id': 1, 'fund_value': 40.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 10.0}]

listC = [{'fund_type_id': 1, 'fund_value': 20.0}, {'fund_type_id': 2, 'fund_value': 50.0}, {'fund_type_id': 3, 'fund_value': 30.0}]

result = [{
    'fund_type_id': a['fund_type_id'],
    'fund_value': a['fund_value'] - b['fund_value']   c['fund_value']
} for a, b, c in zip(listA, listB, listC)] 
print(result)
  •  Tags:  
  • Related