When I query my Mysql table to get results. I get a tuple back.
The tuple is like this:
(('Book 1', 1), ('Book 2', 1), ('Book 1', 2))
How do I get my tuple to be like this:
(('Book 1', 3), ('Book 2', 1))
Any suggestions in python or SQL would be helpful.
CodePudding user response:
you can try SQL group by statement with aggregate function 'sum' example
select book_name,sum(book_quantity)
from your_table_name
group by book_name
CodePudding user response:
Use a dictionary to implement counting and then switch back to tuples
result = {}
tuple_ = (('Book 1', 1), ('Book 2', 1), ('Book 1', 2))
for k, v in tuple_:
result[k] = result.setdefault(k, 0) v
print(tuple(result.items())) # (('Book 1', 3), ('Book 2', 1))
Use defaultdict
from collections import defaultdict
result = defaultdict(int)
for k, v in tuple_:
result[k] = v
print(tuple(result.items()))