I have an error where a Python dictionary doesn’t have a key that is absolutely present.
I have a function to_geojson
which takes various parts of a geopandas dataframe and returns a dictionary with string keys:
to_geojson(gdf).keys()
=> dict_keys(['type', 'geometry', 'properties'])
[type(key) for key in to_geojson(gdf).keys()]
=> [<class 'str'>, <class 'str'>, <class 'str'>]
to_geojson(gdf)['geometry']
=> KeyError: 'geometry'
Converting the output of to_geojson
to a JSON string and back also doesn’t work.
Aside from this, ‘geometry’ has a nested key ‘coordinates’. Again the types check out, but the behavior is again unbelievably strange:
for key in to_geojson(gdf).keys():
if key1 == "geometry":
to_geojson(gdf)[key1] # This doesn't blow up!
for key2 in to_geojson(gdf)[key].keys():
if key2 == "coordinates":
coords = to_geojson(gdf)[str(key2)] # KeyError: 'coordinates'!!