3 ms·
Using `itertools.groupby` will probably give the cleanest solution. Something like this (untested): groups = itertools.groupby(sorted(mylist, key=lambda x:
by Denvercoder9 5y ago
Using `itertools.groupby` will probably give the cleanest solution. Something like this (untested):
groups = itertools.groupby(sorted(mylist, key=lambda x: x['thing']), key=lambda x: x['thing'])
newlist = [{**group[0], 'count': sum(item['count'] for item in group)} for group in groups]
I'm not overly fond of it, having to sort the list for `groupby` is unpleasant and extracting values from dictonaries is verbose. If this was an array of tuples it could be made much more concise, but of course that doesn't allow storing extra information for each thing, which this solution does.
- deleted 5y ago[deleted]