2 ms·
Don't know about elegant. The following doesn't have the O(N^2) performance: def merge_counts(mylist): thing_lookup = {} # map thing -> item
by eesmith 5y ago
Don't know about elegant. The following doesn't have the O(N^2) performance:
def merge_counts(mylist):
thing_lookup = {} # map thing -> item
newlist = []
for item in mylist:
thing = item["thing"]
if thing in thing_lookup:
# seen before; update count.
thing_lookup[thing]["count"] += item["count"]
else:
# first time I've seen this thing
newlist.append(item)
thing_lookup[thing] = item
return newlist
It, like the original, mutates the original dictionary. I would prefer:
# first time I've seen this thing
thing = thing.copy() # don't mutate the original
newlist.append(item)
- deleted 5y ago[deleted]