Skip to content

Instantly share code, notes, and snippets.

Embed
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']].append(row['address'])
else:
by_year[row['date']] = []
by_year[row['date']].append(row['address'])
year_summary = {}
for year in by_year:
year_summary[year] = Counter(by_year[year])
print year_summary
short_way(food)
# long_way(food)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.