0

I have a list of the following tupelets (all in the same format) which I have generated by querying a database:

('topic1', 'Will', 5),
('topic1', 'John', 120),
('topic1', 'John', 15),
('topic8378', 'John', 1),
('topic8378', 'Will', 10),
('topic8378', 'John', 10),
('topic8378', 'Jessica', 5),
('topic8378', 'Will', 1),
('topic15', 'Will', 1),
('topic15', 'John', 1),
('topic15', 'Will', 1),
('topic15', 'Will', 1),
('topic15', 'John', 1),
('topic15', 'John', 1),
('blah10', 'Jessica', 8),
('blah10', 'John', 18),

The third value of these dictionaries is an 'amount' field. I want to accumulate a new list of tupelets by adding total amounts for each person in each topic, so that it (for example) returns a simplified total list per topic (reverse sorted in a list):

('topic1', 'John', 135)
('topic1', 'Will', 10)
('topic8378', 'John', 11)
('topic8378', 'Will', 10)
('topic8378', 'Jessica', 5)
('topic15', 'Will', 3)
('topic15', 'John', 3)
('blah10', 'John', 18)
('blah10', 'Jessica, 8)

Should I use itemgetter in this scenario? What is the best way to cross-check duplicates and accumulate totals for the middle field?

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
cmcjake
  • 159
  • 1
  • 9
  • The question was marked as duplicate before I could post my answer. Here is a PasteBin with a solution using `itertools.groupby` for your case: https://pastebin.com/3CxCPAtK – Pierre Jun 09 '18 at 01:59
  • I'm confused, you used key_topic_name as a function, but in this line: sorted_tuple_list = sorted(tuple_list, key=key_topic_name) You used it as a variable with no arguments? – cmcjake Jun 09 '18 at 02:40
  • `key_topic_name()` is indeed a function, and we are passing it as argument to `sorted()` and `groupby()` as the `key` argument. In Python, everything is an object, and we can pass functions as arguments to other functions. If you want more details about `key`, feel free to check out this [other answer](https://stackoverflow.com/a/32238222/7663649). – Pierre Jun 09 '18 at 02:48
  • It works perfectly. Sorry about the duplicate question - kudos, mate. I was using nested for loops and it just wasn't working out. – cmcjake Jun 09 '18 at 02:52
  • You're welcome, I hope my late answer was helpful! – Pierre Jun 09 '18 at 02:55

0 Answers0