python - How do I sum tuples in a list where the first value is the same? -


i have list of stocks , positions tuples. positive buy, negative sell. example:

p = [('aapl', 50), ('aapl', -50), ('ry', 100), ('ry', -43)] 

how can sum positions of stocks, current holdings?

result = [('aapl', 0), ('ry', 57)] 

how this? can read collections.defaultdict.

>>> collections import defaultdict >>> testdict = defaultdict(int) >>> p = [('aapl', 50), ('aapl', -50), ('ry', 100), ('ry', -43)] >>> key, val in p:         testdict[key] += val   >>> testdict.items() [('aapl', 0), ('ry', 57)] 

Comments

Popular posts from this blog

vb.net - Alternative to the T-SQL AS keyword -

php - MySQLi binding parameters in a prepared statement doesn't work unless inserted after "WHERE" -

ios - CFRelease causing crash in iPad application -