Skip to content

Instantly share code, notes, and snippets.

@venkat
Created February 15, 2017 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save venkat/7cddbc7c792a40b256b254d1a0091dee to your computer and use it in GitHub Desktop.
Save venkat/7cddbc7c792a40b256b254d1a0091dee to your computer and use it in GitHub Desktop.
Output per-county tab-separated information
#!/bin/env python
#data downloaded from https://data.opendatasoft.com/explore/dataset/usa-2016-presidential-election-by-county@public/download/?format=json&timezone=America/New_York
import json
def get_liveability_info(db, county_state_to_recordid_map, state_county):
record_ids = county_state_to_recordid_map[state_county]
if len(record_ids) != 1:
print 'not a 1:1 mapping between state, county to record'
county = record_ids[0]
if 'white_not_latino_population' not in db[county]['fields']:
white_not_latino_population = 50
else:
white_not_latino_population = db[county]['fields']['white_not_latino_population']
return (db[county]['fields']['rep16_frac'], white_not_latino_population)
def main():
db = {}
county_state_to_recordid_map = {}
for record in json.load(open('usa-2016-presidential-election-by-county.json')):
if 'st' in record['fields']:
st = record['fields']['st']
else:
st = ''
county_state_to_recordid_map.setdefault((st, record['fields']['county']), []).append(record['recordid'])
db[record['recordid']] = record
liveability_info_all_counties = []
for state_county in county_state_to_recordid_map:
liveability_info = get_liveability_info(db, county_state_to_recordid_map, state_county)
liveability_info_all_counties.append((
liveability_info[0],
liveability_info[1],
state_county[0],
state_county[1]))
for liveability_info in liveability_info_all_counties:
print '%s\t%s\t%s\t%s' % liveability_info
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment