Home > Back-end >  How can I sum up dictionaries in a list (python)?
How can I sum up dictionaries in a list (python)?

Time:01-24

I have the following list which contains several dictionaries.

item_list = [{'item': 'apple', 'amount': 200}, {'item': 'apple', 'amount': 150}, {'item': 'orange', 'amount': 300}]

I want to sum up the amount of each item. How can I do that without using Counter?

The desired output would be

[{'item': 'apple', 'amount': 350},  {'item': 'orange', 'amount': 300}]

CodePudding user response:

You can use a temporary dictionary to hold the sum and recreate the original structure

from collections import defaultdict

item_list = [{'item': 'apple', 'amount': 200}, {'item': 'apple', 'amount': 150}, {'item': 'orange', 'amount': 300}]

sumdict = defaultdict(int)

for item in item_list:
  sumdict[item['item']]  = item['amount']

result = [{'item': k, 'amount': v} for k,v in sumdict.items()]
print(result)

CodePudding user response:

You can first select your items and then go over each item and get the amount of them:

item_list = [{'item': 'apple', 'amount': 200}, {'item': 'apple', 'amount': 150}, {'item': 'orange', 'amount': 300}]
keys = set([ele['item'] for ele in item_list]) # Use set to get the unique keys
d = dict()
for k in keys:
    d[k] = sum( [ ele['amount'] for ele in item_list if ele['item'] == k ] )
>>> {'orange': 300, 'apple': 350}

First one get the unique set of all items in each dictionary. The new variable d is a new dictionary where the keys are the items of the first dictionary. At the end sum all items.

Or in an other format (but you can change it how you like):

item_list = [{'item': 'apple', 'amount': 200}, {'item': 'apple', 'amount': 150}, {'item': 'orange', 'amount': 300}]
keys = set([ele['item'] for ele in item_list]) # Use set to get the unique keys
d = list()
for k in keys:
    d.append({'item': k, 'amount': sum( [ ele['amount'] for ele in item_list if ele['item'] == k ] ) } )
>>> [{'item': 'orange', 'amount': 300}, {'item': 'apple', 'amount': 350}]

CodePudding user response:

Without using any module, create an indexed dict by item name then extract the list of values:

new_item_dict = {}
for i in item_list:
    d = new_item_dict.setdefault(i['item'], {'item': i['item'], 'amount': 0})
    d['amount']  = i['amount']
new_item_list = list(new_item_dict.values())

Output:

>>> new_item_list
[{'item': 'apple', 'amount': 350},
 {'item': 'orange', 'amount': 300}]

CodePudding user response:

You should try something like this:

itemToSum = 'apple' 
sum = 0

for dictionary item_list:
    if itemToSum in dictionary.values():
        amount = dictionary.get(item_list('amount')
        sum = sum   amount

Basically what you do is check every dictionary in the array if it has the value that you want to count, if yes you count the value. Other answers may suggest using an external library but you can get the job done without using any

CodePudding user response:

This is probably overkill but you could use Pandas.

import pandas as pd

item_list = [
    {'item': 'apple', 'amount': 200}, 
    {'item': 'apple', 'amount': 150},
    {'item': 'orange', 'amount': 300}
]

df = pd.DataFrame(item_list)
totals = df.groupby("item").sum()
summed_list = [{'item': item, 'amount': values['amount']} 
               for item, values in totals.iterrows()]
print(summed_list)

Alternatively:

df = pd.DataFrame(item_list)
totals = df.groupby("item").sum()
summed_list = totals.reset_index().to_dict('records')
print(summed_list)

CodePudding user response:

from collections import defaultdict

item_amount = defaultdict(lambda: 0)

for item in item_list:
    name, amount = item['item'], item['amount']
    item_amount[name]  = amount

item_amount = [{'item': name, 'amount': amount} for name, amount in item_amount.items()]

item_amount
  •  Tags:  
  • Related