Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
from collections import Counter, defaultdict
food = [{'date':'2014', 'address':'sesame street'},{'date':'2012', 'address':'eversholt street'},{'date':'2013', 'address':'eversholt street'},{'date':'2014', 'address':'eversholt street'},{'date':'2012', 'address':'sesame street'},{'date':'2013', 'address':'sesame street'},{'date':'2014', 'address':'sesame street'},{'date':'2014', 'address':'eversholt street'},{'date':'2014', 'address':'sesame street'}]
def short_way(food):
## a default dict sets the value type to the
by_year = defaultdict(Counter)
for row in food:
# print by_year
## simultaneously adds the date as a key to the dict and incremements the counter value for the address to += 1
by_year[row['date']][row['address']] += 1
print by_year
def long_way(food):
by_year = {}
for row in food:
if row['date'] in by_year:
by_year[row['date']] = []
year_summary = {}
for year in by_year:
year_summary[year] = Counter(by_year[year])
print year_summary
# long_way(food)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment