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
Post a Comment