Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Last active December 23, 2021 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hughdbrown/932ba1d90e6583c99ec14b41abc24ce0 to your computer and use it in GitHub Desktop.
Save hughdbrown/932ba1d90e6583c99ec14b41abc24ce0 to your computer and use it in GitHub Desktop.
Alternative sum of list of dictionaries
# O(n) alternative to:
# https://elisabethirgens.github.io/notes/2021/12/step-away/
from collections import defaultdict
mylist = [
{'thing': 'A', 'count': 4},
{'thing': 'B', 'count': 2},
{'thing': 'A', 'count': 6},
]
tmp = defaultdict(int)
for d in mylist:
tmp[d['thing']] += d['count']
mylist = [{'thing': key, 'count': value} for key, value in tmp.items()]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment