wasabi_012
wasabi_012

Reputation: 33

How can I sum up dictionaries in a list (python)?

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

Upvotes: 1

Views: 129

Answers (7)

Aivar Paalberg
Aivar Paalberg

Reputation: 5157

One way is: "try to add amount to item, if not item then add record and item". This requires one iteration over item_list and preserves whole record (dictonary in item_list) and relies on list indices (indice of dictionary in output list corresponds to item indice in seen list):

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

output = []
seen = []

for item in item_list:
    try:
        output[seen.index(item['item'])]['amount'] += item['amount']
    except ValueError:
        output.append(item)
        seen.append(item['item'])

Upvotes: 0

Sdq
Sdq

Reputation: 21

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

Upvotes: 0

Bill
Bill

Reputation: 11643

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)

Upvotes: 0

Emilio
Emilio

Reputation: 132

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

Upvotes: 0

Shanavas M
Shanavas M

Reputation: 1629

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)

Upvotes: 1

Corralien
Corralien

Reputation: 120559

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

Upvotes: 0

3dSpatialUser
3dSpatialUser

Reputation: 2406

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

Upvotes: 0

Related Questions