You need to enable JavaScript to run this app. Python如何过滤Google Places API返回列表中无place_id的条目
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 14:57:02