where the total is now a total of the types for each customer/group.
Needs to be done client side if at all possible, and I want to avoid using database queries as the query takes ages (that’s another problem). Happy to use any library that can run client side (Pandas?) but I just cannot claw hammer my head to work out why.
Can anyone help please?
EDIT - In SQL I would be doing this :
SELECT name, group, sum(totals) FROM table GROUP BY name, group
but how do I use multiple values in the lambda function (to replace itemgetter)? I’m reading up on lambdas but if you can short circuit my ham fisted blundering
@owen.campbell - you are a star - I had tried that (I do try) but I’d got my brackets in a muddle.
It all works! Thank you so much. Here’s what I actually used :
def grouper(item):
return(item['name'], item['group'])
result = [
{key: sum(item["totals"] for item in name)}
for key, name in groupby(
sorted(test, key=grouper), key=grouper
)
]
(which is exactly what you just wrote - that’s how addled my head is today, I thought I’d changed it!)
I have one last question - how can I format the result into an array of dicts again?
The result comes back like this :
[
{
('dave' : 'group1') : 200
}
]
with the grouping tuple as the key. I can obviously step through it and recreate an items list that I can feed to a repeating panel, but is there anyway to return the data in that format?
Just change the comprehension to do whatever you need. e.g.:
result = [
{"name": key[0], "group": key[1], "totals": sum(item["totals"] for item in group)}
for key, group in groupby(sorted(test, key=grouper), key=grouper)
]