Created
September 1, 2016 15:57
-
-
Save flashton2003/8f71bfe2bbd01ade9d4cbc795234c0f5 to your computer and use it in GitHub Desktop.
This file contains 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
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