Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict comprehension summing from objects

Tags:

python

Given a setup like this:

class Foo():
   state = 'x'
   amount = 1


a = Foo()
b = Foo()
c = Foo()
c.state = 'y'
foos = [a, b, c]

I want to get a dict that has keys = object.state, values = sum(object.amounts of objects with that state). In this case:

{'x': 2, 'y': 1}

I want to do this automatically, so I don't need to know the different possible states in advance.

For sure I could iterate through in some boring manner like this:

my_dict = {}
for foo in foos:
    try:
        my_dict[foo.state] += foo.value
    except (KeyError, TypeError):
        my_dict[foo.state] = foo.value 

But that is a bit verbose, and I'm wondering if there's a nicer way to do it, maybe with dict comprehensions or something, but my efforts so far have been in vain.

like image 481
Tom Carrick Avatar asked Mar 25 '26 21:03

Tom Carrick


2 Answers

How about Counter:

>>> from collections import Counter
>>>
>>> foos = [a,b,c]
>>> 
>>> c = Counter()
>>> for x in foos:
        c[x.state] += x.amount


>>> c
Counter({'x': 2, 'y': 1})
like image 147
Iron Fist Avatar answered Mar 28 '26 11:03

Iron Fist


Dictionary comprehension is not the most optimized approach in this case. Instead you can use collections.defaultdict() like following :

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> 
>>> for obj in foos:
...     d[obj.state] += obj.amount
... 
>>> d
defaultdict(<type 'int'>, {'y': 1, 'x': 2})
like image 28
Mazdak Avatar answered Mar 28 '26 10:03

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!