Python中如何从Google API返回结果获取经纬度?
获取Google API返回的经纬度信息
没问题,我来帮你搞定这个!既然geocode_result是列表类型,而第一个元素geocode_result[0]是字典,那我们只需要逐层通过字典的键来访问就可以了,不用列表索引(因为这里的结构是嵌套字典,不是列表)。
具体的代码实现可以这样写:
# 先取出列表里的第一个字典元素 result_dict = geocode_result[0] # 逐层获取经纬度 latitude = result_dict['geometry']['location']['lat'] longitude = result_dict['geometry']['location']['lng'] # 打印验证一下 print(f"纬度: {latitude}, 经度: {longitude}")
或者更简洁一点,直接链式访问:
lat = geocode_result[0]['geometry']['location']['lat'] lng = geocode_result[0]['geometry']['location']['lng']
如果担心某个键可能不存在(比如API返回结果有异常),可以用字典的get()方法来避免KeyError,让代码更健壮:
lat = geocode_result[0].get('geometry', {}).get('location', {}).get('lat', None) lng = geocode_result[0].get('geometry', {}).get('location', {}).get('lng', None)
这样如果某个层级的键不存在,会返回None而不是直接抛出错误。
内容的提问来源于stack exchange,提问作者Raphael
相关产品推荐
相关产品推荐

