Python如何过滤Google Places API返回列表中无place_id的条目
解决方法
报错原因
你之前的代码是用于遍历字典的推导式,但你拿到的Google Places API返回结果最外层是列表类型,不存在字典专属的items()方法,因此会抛出AttributeError。
过滤实现
你可以根据自己的需求选择以下两种过滤方案:
方案1:仅提取所有有效place_id值
适合只需要place_id后续使用的场景:
# 假设你的原始API返回列表变量名为 api_results place_ids = [ res["candidates"][0]["place_id"] for res in api_results if res.get("candidates") # 过滤掉candidates为空的条目 ]
执行后得到的place_ids输出为:
['ChIJ2YPts0rGUIYRHZkmh8TxBT4', 'ChIJ9_uV17leXIYRgQc7NludRdw', 'ChIJWVukvUKvw4cRFGFVXGHNX9A', 'ChIJ1VXMS8i_9YgR6NTQL_9BKMs', 'ChIJ79Q4K1YAQIgRe-WjYCw9MuM', 'ChIJ8WoxTJ7qQIYRDZX5JBrofUw']
方案2:保留完整的有效条目结构
适合需要保留原始返回的status、candidates完整结构的场景,仅过滤掉无结果的条目:
valid_entries = [ res for res in api_results if res.get("status") == "OK" and res.get("candidates") ]
注:Google Places Find Place接口默认
candidates列表最多返回1个结果,上述写法已适配官方返回规则,若你调用的是其他返回多候选的接口,可自行扩展遍历candidates列表的逻辑。
内容的提问来源于stack exchange,提问作者Kushal Mohnot
相关产品推荐
相关产品推荐

