You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套列表转字典并在for循环调用值报错的解决方法

解决方法

核心问题是没把原始列表里的字符串正确转成字典,同时循环逻辑也出错,导致没法用字符串索引访问键值。以下是具体修正步骤:

1. 把原始数据转成字典列表

原始geos的每个子列表里是类似字典格式的字符串,用ast.literal_eval(比eval更安全)把它转换成真正的字典:

import ast

geos = [["'latitude': 12.1234, 'longitude': -12.1234, 'accuracy': 100"],
        ["'latitude': 12.1233, 'longitude': -12.1233, 'accuracy': 100"],
        ["'latitude': 12.1222, 'longitude': -12.1111, 'accuracy': 100"],
        ["'latitude': 12.1111, 'longitude': -12.1222, 'accuracy': 100"]]

# 转换为字典列表
converted_geos = [ast.literal_eval(f"{{{item[0]}}}") for item in geos]

2. 修正循环逻辑

你之前的循环错误覆盖了变量,也没遍历真正的字典列表,修正后的代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = Options()
options.add_argument("--headless")
# 把driver初始化放在循环外,避免重复创建浏览器实例
driver = webdriver.Chrome(service=Service('/Library/path/chromedriver'), options=options)
driver.execute_cdp_cmd("Browser.grantPermissions", {
    "origin": "https://www.google.com",
    "permissions": ["geolocation"]
})

for geo in converted_geos:
    # 现在geo是真正的字典,直接用键名取值即可
    driver.execute_cdp_cmd("Emulation.setGeolocationOverride", {
        "latitude": geo["latitude"],
        "longitude": geo["longitude"],
        "accuracy": geo["accuracy"]
    })
    driver.get("https://www.google.com")
    # 这里可以添加页面操作逻辑,比如元素定位、数据提取等

driver.quit()  # 循环结束后关闭浏览器

错误原因说明

  • 你之前写的geos_dict = {geo[0]:None for geo in geos}生成的是「以地理字符串为键、值为None」的字典,根本不是存储地理信息的字典集合。
  • 循环里enumerate(geos_dict)遍历的是字典的键(也就是那些地理字符串),还错误覆盖了geos_dict变量,自然没法用geo["latitude"]这种字符串索引访问。
  • 只有把字符串解析成真正的字典后,才能通过键名获取对应的值。

内容的提问来源于stack exchange,提问作者VRapport

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:10:28