101

I have got pretty simple list:

example_list = [
    {'points': 400, 'gold': 2480},
    {'points': 100, 'gold': 610},
    {'points': 100, 'gold': 620},
    {'points': 100, 'gold': 620}
]

How can I sum all gold values? I'm looking for nice oneliner.

Now I'm using this code (but it's not the best solution):

total_gold = 0
for item in example_list:
    total_gold += example_list["gold"]
Mateusz Jagiełło
  • 6,854
  • 12
  • 40
  • 46
  • 6
    You shouldn't use `list` as the name of a local variable - doing so shadows the built-in `list` type and can cause problems. – g.d.d.c Jul 27 '12 at 17:23
  • 2
    You're right, I'm use this only for this example. – Mateusz Jagiełło Jul 27 '12 at 17:25
  • @sigo -- In this case, a nice one-liner exists, but generally, restricting answers to "nice one-liners" is probably a bad idea (as nicer multi-liners might exist). – mgilson Jul 27 '12 at 17:28

5 Answers5

221
sum(item['gold'] for item in myList)
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
30

If you're memory conscious:

sum(item['gold'] for item in example_list)

If you're extremely time conscious:

sum([item['gold'] for item in example_list])

In most cases just use the generator expression, as the performance increase is only noticeable on a very large dataset/very hot code path.

See this answer for an explanation of why you should avoid using map.

See this answer for some real-world timing comparisons of list comprehension vs generator expressions.

Community
  • 1
  • 1
Ben Burns
  • 14,978
  • 4
  • 35
  • 56
  • why does a similar `sum(item.gold for item in example_list)` not work? I get a `AttributeError: 'dict' object has no attribute 'gold'` – cryanbhu Nov 06 '20 at 12:08
  • 2
    Because the dict type has no attribute (type member) named 'gold'. You're probably confusing Python for JavaScript. In JS, you can use either dot notation or index notation, as the dict-like object there is generally just a plain old JS object. In Python dicts are dicts, and you must use the index operator, so, long answer long: you want `item['gold']` instead of `item.gold`. – Ben Burns Nov 08 '20 at 04:27
8

If you prefer map, this works too:

 import operator
 total_gold = sum(map(operator.itemgetter('gold'),example_list))

But I think the generator posted by g.d.d.c is significantly better. This answer is really just to point out the existence of operator.itemgetter.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 5
    `_reduce = lambda fn, ar: fn( ar[0], _reduce(fn, ar[1:])) if len(ar) > 1 else ar[0]` `total_gold = _reduce((lambda x, y: x + y), (lambda fn, ar: [fn(ar[i]) for i in xrange(len(ar))])( (lambda x: x["gold"]), example_list))` I also think g.d.d.c's answer is good. This answer is really just to point out the existence of lambda :P – Moop Jul 27 '12 at 18:07
  • 1
    thanks -- comment formatting doesn't seem to respect newlines though, so it looks even worse than it should. – Moop Jul 27 '12 at 18:11
  • @Filipq -- Really, I posted the same answer as g.d.d.c did ~30 seconds after he did. I originally deleted it, but ever since I got the stupid moderator tools, I can still see my deleted answer. It was bugging me, so I thought to myself, there has to be another somewhat clean way to do this that illustrates something useful ... I probably should just delete it though ... I don't know. (I'm open to suggestions). – mgilson Jul 27 '12 at 18:14
5
from collections import Counter
from functools import reduce
from operator import add

sum_dict = reduce(add, (map(Counter, example_list)))
# Counter({'points': 700, 'gold': 4330})
total_gold = sum_dict['gold']
Bruno Mello
  • 4,448
  • 1
  • 9
  • 39
xmduhan
  • 965
  • 12
  • 14
  • nice, this allows for counting arbitrary items in the dict without having to know all keys (e.g. this would support counting all keys in the dict at once without specifying them all). – mdmjsh May 31 '22 at 10:55
0
example_list = [
    {'points': 400, 'gold': 2480},
    {'points': 100, 'gold': 610},
    {'points': 100, 'gold': 620},
    {'points': 100, 'gold': 620}
]

result = np.sum([x['gold'] for x in example_list])


print(result)

output

 4330
Golden Lion
  • 3,840
  • 2
  • 26
  • 35