I'm attempting to use the Google Maps Geocoding API to find the State associated with a latitude and longitude with a Python script. I have no trouble getting back a response from the server, but when I do, I'm having trouble extracting the information I need.
This is my code:
from pymongo import MongoClient
import googlemaps
client = MongoClient()
turnkey = "MYVERYSECRETAPICODEWOOOOOOOOO"
gmaps = googlemaps.Client(key=turnkey)
lat = 29
long = -98.4936
#This code runs fine:
geocode = gmaps.reverse_geocode((lat, long))
print(geocode[0]['address_components'])
print("
")
print(geocode[0]['address_components'][0])
print(geocode[0]['address_components'][0]["types"])
#This Code Is a Problem:
for i in geocode[0]['address_components'][:]:
print(geocode[0]["address_components"][i])
if 'administrative_area_level_1' in geocode[0]['address_components'][i]['types'] :
print(geocode[0]['address_components'][i]['long_name'])
The response I receive back is:
Traceback (most recent call last):
[{'long_name': '6476', 'short_name': '6476', 'types': ['street_number']}, {'long_name': 'East Fm 476', 'short_name': 'E Fm 476', 'types': ['route']}, {'long_name': 'Pleasanton', 'short_name': 'Pleasanton', 'types': ['locality', 'political']}, {'long_name': 'Atascosa County', 'short_name': 'Atascosa County', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Texas', 'short_name': 'TX', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'United States', 'short_name': 'US', 'types': ['country', 'political']}, {'long_name': '78064', 'short_name': '78064', 'types': ['postal_code']}]
File "C:/Users/Pendelluft/Documents/CodeyMcCodeFace/CodeyCode/SNAKESSSSS/SingleQuery.py", line 24, in <module>
print(geocode[0]["address_components"][i])
{'long_name': '6476', 'short_name': '6476', 'types': ['street_number']}
['street_number']
TypeError: list indices must be integers or slices, not dict
Process finished with exit code 1
What I don't get is WHY it works fine when I ask it to print geocode[0]['address_components'][0]["types"], but complains I'm treating a list like a dictionary when I try geocode[0]['address_components'][i]['types'] .
Any help would be greatly appreciated, and thank you all so much for your time.
See Question&Answers more detail:
os