Last active
November 24, 2021 18:22
-
-
Save cjwinchester/a8ff5dee9c07d161bdf4 to your computer and use it in GitHub Desktop.
Two Python functions -- one to return a dictionary of U.S. county FIPS codes, another to return a JSON array of objects of county adjacency data.
This file contains hidden or 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
| import requests | |
| import csv | |
| import json | |
| def getCounties(): | |
| "Function to return a dict of FIPS codes (keys) of U.S. counties (values)" | |
| d = {} | |
| r = requests.get("http://www2.census.gov/geo/docs/reference/codes/files/national_county.txt") | |
| reader = csv.reader(r.text.splitlines(), delimiter=',') | |
| for line in reader: | |
| d[line[1] + line[2]] = line[3].replace(" County","") | |
| return d | |
| def getCountyAdj(): | |
| "Return a list of dicts where each dict has a county FIPS code (key) and a list of FIPS codes of the adjacent counties, not including that county (value)" | |
| adj = requests.get("http://www2.census.gov/geo/docs/reference/county_adjacency.txt") | |
| adj_data = adj.text.encode("utf-8") | |
| reader = csv.reader(adj_data.splitlines(), delimiter='\t') | |
| ls = [] | |
| d = {} | |
| countyfips = "" | |
| for row in reader: | |
| if row[1] and row[1] != "": | |
| if d: | |
| ls.append(d) | |
| d = {} | |
| countyfips = row[1] | |
| d[countyfips] = [] | |
| "Grab the record on the same line" | |
| try: | |
| st = row[3] | |
| if st != countyfips: | |
| d[countyfips].append(st) | |
| except: | |
| pass | |
| else: | |
| "Grab the rest of the records" | |
| if row[3] and row[3] != "": | |
| st = row[3] | |
| if st != countyfips: | |
| d[countyfips].append(st) | |
| return json.dumps(ls) |
just what I was looking for, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kudos for the getCounties function. Saved me some time.