Find the county for a city, state

Eyal S. picture Eyal S. · May 26, 2017 · Viewed 11.2k times · Source

I have a city + state information and I'm trying to find the county. I tried a few things. The closest I got is using geopy. Here is an example:

from geopy.geocoders import Nominatim
geolocator = Nominatim()
loc = geolocator.geocode('Chicago Illinois')
print(loc.address)
# u'Chicago, Cook County, Illinois, United States of America'
loc = geolocator.geocode('San Francisco California')
print(loc.address) 
# u'SF, California, United States of America'

The problem is that it is unclear if the county is part of the output and if it is how to extract it using code (the string format seems to change).

What is the best way to get County information for a city + state?

Answer

Michael James Kali Galarnyk picture Michael James Kali Galarnyk · May 18, 2018

Here is a geocoder solution that will help you get the county data. If you don't already have it installed, you can pip install geocoder.

import geocoder

results = geocoder.google("Chicago, IL")

print(results.current_result.county)

enter image description here