3 ms·
Agreed with marginalia_ru, if you can get the DB to do it, that's probably the place. if not, I'd go with d = collections.defaultdict(int) for item in
by detaro 5y ago
Agreed with marginalia_ru, if you can get the DB to do it, that's probably the place. if not, I'd go with
d = collections.defaultdict(int)
for item in mylist:
d[item["thing"]] += item["count"]
newlist = [{"thing": key, "count": value} for key, value in d.items()]
(I'm assuming the order doesn't matter, and the specific output format is needed. E.g. if the next step then iterates over that list and unpacks it, obviously get rid of the last line and use the dict)
There is the collections.Counter type, but I think there's not really a beneficial way of using that here.
Generally, the "there is one elegant solution" aspect of Python is widely overstated :D
- YurgenJurgensen 5y agoI think this defaultdict solution is the best, or at least most pythonic. I really thought if this was possible to do in a single dictionary comprehension, with some kind of d = {k: sum(v) for k, v in <something>}, but whatever goes in <something> ends up being super ugly.
- runekaagaard 5y agoWhat you do mean ugly :) [{"thing": k, "count": v} for k, v in [[c, c.update({x["thing"]: x["count"]})] for c in [Counter()] for x in response][0][0].items()]
- Denvercoder9 5y agoNote that this approach doesn't work as nicely if you need to store additional information alongside the name and count.
- qsort 5y agoIf you need to store other info, it doesn't make sense to aggregate. Think of it in SQL: SELECT a, b, SUM(c) FROM table GROUP BY a doesn't even compile. You either project away `b` or group over both `a` and `b`.
- Denvercoder9 5y agoThat's true, but while in SQL you can easily group by `a` and `b`, here that's difficult (you'll need to key the dict by a tuple of the values, and reassemble the dictionary afterwards, or something like that).
- qsort 5y agoYeah, fair enough. You'd have the same problem with any approach, though. In a sense, that's easy in SQL only because the hash-magic is abstracted away.
- deleted 5y ago[deleted]