Skip to content

Instantly share code, notes, and snippets.

@rwilleynyc
Last active September 17, 2019 15:58
Show Gist options
  • Select an option

  • Save rwilleynyc/454b471b9dda1d2184cd6ff19f6517a7 to your computer and use it in GitHub Desktop.

Select an option

Save rwilleynyc/454b471b9dda1d2184cd6ff19f6517a7 to your computer and use it in GitHub Desktop.
Get list of neighboring states and save to dictionary
import urllib.request
url = 'https://github.com/ritvikmath/StarbucksStoreScraping/raw/master/us_states.geojson'
urllib.request.urlretrieve(url, 'international_data/us_states.geojson')
#manipulate complex shapes
from shapely.geometry import Polygon, MultiPolygon
#manipulate json objects
import json
#open up the US States Geojson
with open('international_data/us_states.geojson') as f:
states = json.load(f)
#initialize a dictionary to store the state shape info
statePolygons = {}
#for each state ...
for stateInfo in states['features']:
#get the state name
stateName = stateInfo['properties']['NAME']
#the state geography is either a Polygon (some shape) or a MultiPolygon (a collection of polygons)
stateGeographyType = stateInfo['geometry']['type']
#if it's a Polygon, convert the coordinates to a shapely Polygon object
if stateGeographyType == 'Polygon':
stateGeometry = Polygon(stateInfo['geometry']['coordinates'][0])
#if its a MultiPolygon, convert each contained polygon into a shapely Polygon object ...
#and then store the list of Polygons in a shapely MultiPolygon object
elif stateGeographyType == 'MultiPolygon':
polygonsInMultipolygon = [Polygon(p[0]) for p in stateInfo['geometry']['coordinates']]
stateGeometry = MultiPolygon(polygonsInMultipolygon)
#store the state geography info in the dictionary
statePolygons[stateName] = stateGeometry
# Create dictionary for saving neighbors
neighbors = {}
#for each state ...
for k1,v1 in statePolygons.items():
neighbors[k1] = []
#iterate over each other state
for k2,v2 in statePolygons.items():
#if the states touch, then add this state to the list of neighboring states
if v1.touches(v2):
neighbors[k1].append(k2)
# Display first 5 results
for state in sorted(neighbors.keys())[:5]:
print(f'{state}: {neighbors[state]}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment