Skip to content

Instantly share code, notes, and snippets.

@heyitsjames
Created August 22, 2015 00:11
Show Gist options
  • Select an option

  • Save heyitsjames/a440161cae1e737752c7 to your computer and use it in GitHub Desktop.

Select an option

Save heyitsjames/a440161cae1e737752c7 to your computer and use it in GitHub Desktop.
% married by per capita, where per capita is defined as an individual > 18 years old.
import requests
import json
def test_api():
state_list = list(range(1, 52))
key = '76e9012372312829bbfd506cd2b9dcff63c58e75'
params = 'NAME,P0180003,P0100001'
url = 'http://api.census.gov/data/2010/sf1?key={0}&get={1}&for=state:{2}'
state_data = []
for state in state_list:
r = requests.get(url.format(key, params, str(state).zfill(2)))
if r.text:
data = json.loads(r.text)[1]
state, num_households, total_population_over_18 = (data[0], int(data[1]), int(data[2]))
num_married = num_households * 2
percentage_married = (num_married / total_population_over_18) * 100
formed_data = {
'state': state,
'number_of_married': num_married,
'total_population_over_18': total_population_over_18,
'percentage_married': percentage_married
}
state_data.append(formed_data)
if state_data:
sorted_state_data = sorted(state_data, key=lambda k: k['percentage_married'], reverse=True)
for index, state_data in enumerate(sorted_state_data):
print(index + 1,
state_data['state'],
"{:.2f}%".format(state_data['percentage_married']))
test_api()
@heyitsjames

Copy link
Copy Markdown
Author

In order to run this script, you will need to install the requests module, via pip or by source. Then run python census.py and you'll see the full list of states, ranked by marriage percentage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment