This should do it:
>>> with open('filename') as f:
dic = {}
for line in f:
name, quan, dt = line.split()
dic.setdefault(name, []).append((dt, quan))
...
>>> for k, v in dic.items():
total = sum(int(x[1]) for x in v)
print '{} {} {}'.format(total, k, ' '.join('{}:{}'.format(x, y) for x, y in v))
...
100 apple 12012013:10 12022013:20 12042013:30 12032013:40
If the data with same product is always grouped together than you can also use itertools.groupby
:
>>> from itertools import groupby
>>> with open('abc1') as f:
for k, g in groupby(f, key=lambda x:x.split()[0]):
data = [x.split()[1:] for x in g]
total = sum(int(x[0]) for x in data)
print '{} {} {}'.format(total, k, ' '.join('{}:{}'.format(y, x) for x, y in data))
...
100 apple 12012013:10 12022013:20 12042013:30 12032013:40
Update:
If the input is coming from a file stream then you can use sys.stdin
:
import sys
from itertools import groupby
for k, g in groupby(sys.stdin, key=lambda x:x.split()[0]):
...