If I have list of tuples like this:
my_list = [(\'books\', \'$5\'), (\'books\', \'$10\'), (\'ink\', \'$20\'), (\'paper\', \'$15\'), (\'paper\', \'$20\'), (\'pap
You can simply use a dictionary to solve this problem.
my_list = [('books', '$5'), ('books', '$10'), ('ink', '$20'),
('paper', '$15'), ('paper', '$20'), ('paper', '$15')]
sums = {}
for item, price in my_list:
sums[item] = sums.get(item, 0) + int(price[1:])
print sums
And if you need list of tuples, just do
print sums.items()
And to get your the output you expect,
print [(item, '$' + str(price)) for item, price in sums.items()]
Update
If you have costs with floating point value, you can simply change int
to float
like this and rest of the code remains the same,
sums[item] = sums.get(item, 0) + float(price[1:])