3 ms·
Something a bit more beginner friendly: agg = {} for item in mylist: if item['thing'] in agg: agg[item['thing']] += item['count'] e
by DangitBobby 5y ago
Something a bit more beginner friendly:
agg = {}
for item in mylist:
if item['thing'] in agg:
agg[item['thing']] += item['count']
else:
agg[item['thing']] = item['count']
result_list = []
for key, value in agg.items():
result_list.append(dict(thing=key, count=value))
In beginner land, reduce makes your eyes glaze over and dict.get(key, default) is understandable in principle but still confusing in practice.
- Izkata 5y agoAfter almost a decade doing python, I'd probably use a plain loop like this but with ".get(key, default)"
- mcv 5y agoWith the recent changes in Javascript, I've developed an aversion to old fashioned for-loops. I prefer to .map.reduce.filter and if absolutely necessary, .forEach my way through the problem.