Jonathan Pirca
Jonathan Pirca

Reputation: 31

How to SUM elements within a list of objects in python

I am trying to sum (plus other maths operations) a specific attribute of my list of objects and I do not know how to do it.

A example of what I am trying to do is:

my_list = [
             {
               'brand': 'Totoya',
               'quantity': 10
             },
             {
               'brand': 'Honda',
               'quantity': 20
             },
             {
               'brand': 'Hyundai',
               'quantity': 30
             }
           ]

I want to SUM all the 'quantity'. Is it possible without a loop? using collections? Counter?

Output = 60

Upvotes: 0

Views: 2009

Answers (3)

gold_cy
gold_cy

Reputation: 14216

Another alternative way to do this

from operator import itemgetter

getter = itemgetter('quantity')
sum(map(getter, my_list))

Upvotes: 0

Erik
Erik

Reputation: 909

Python contains good functions for functional programming.

my_list = ...

# Select the quantities from my_list
quantities = map(lambda x: x['quantity'], my_list) 
# Computes the sum of quantities
total = sum(quantities)

Upvotes: 1

Reznik
Reznik

Reputation: 2806

as the input is:

my_list = [
             {
               'brand': 'Totoya',
               'quantity': 10
             },
             {
               'brand': 'Honda',
               'quantity': 20
             },
             {
               'brand': 'Hyundai',
               'quantity': 30
             }
           ]

You can loop over it as this:

counter = 0
for i in my_list:
    counter += i['quantity']
print(counter)

or in oneliner:

print(sum(i['quantity'] for i in my_list))

Upvotes: 4

Related Questions