I have a list of stocks and positions as tuples. Positive for buy, negative for sell. Example:
p = [(\'AAPL\', 50), (\'AAPL\', -50), (\'RY\', 100), (\'RY\',
Here is a solution that doesn't involve importing:
>>> p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)]
>>> d = {x:0 for x,_ in p}
>>> for name,num in p: d[name] += num
...
>>> Result = map(tuple, d.items())
>>> Result
[('AAPL', 0), ('RY', 57)]
>>>
Note this is for Python 2.x. In 3.x, you'll need to do: Result = list(map(tuple, d.items()))
.