Last active
December 23, 2021 17:48
-
-
Save hughdbrown/932ba1d90e6583c99ec14b41abc24ce0 to your computer and use it in GitHub Desktop.
Alternative sum of list of dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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