Skip to content

Instantly share code, notes, and snippets.

@isaquealves
Created April 10, 2015 05:02
Show Gist options
  • Save isaquealves/757eeb67f0deb81e9710 to your computer and use it in GitHub Desktop.
Save isaquealves/757eeb67f0deb81e9710 to your computer and use it in GitHub Desktop.
Given a dictionary list, creates a new list with grouped dictionaries based on a single key (label) and summing the value of other dictionary fields as convenient
import itertools
item_list = [
{'counter1': 1, 'label': '20150408154801', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154801', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154801', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154819', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154819', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154819', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154819', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154841', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154841', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154841', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408154841', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408155336', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408155336', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408155336', 'counter2': 0, 'counter3': 0},
{'counter1': 1, 'label': '20150408155336', 'counter2': 0, 'counter3': 0},
{'counter1': 0, 'label': '20150408155336', 'counter2': 1, 'counter3': 0},
{'counter1': 0, 'label': '20150408155336', 'counter2': 1, 'counter3': 0},
{'counter1': 0, 'label': '20150408155336', 'counter2': 0, 'counter3': 1},
{'counter1': 0, 'label': '20150408155336', 'counter2': 0, 'counter3': 1},
{'counter1': 0, 'label': '20150408155336', 'counter2': 1, 'counter3': 0},
{'counter1': 0, 'label': '20150408155336', 'counter2': 1, 'counter3': 0}]
grouped_dicts = []
summable = ['counter1', 'counter2', 'counter3']
for s in summable:
for key, group in itertools.groupby(item_list, lambda d: d['label']):
d[s] = sum([d[s] for d in group])
if d not in grouped_dicts:
grouped_dicts.append(d)
print grouped_dicts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment