[英]Converting a list of lists to a dictionary and calling values using a for loop
我有一个单元素列表列表:
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"]]
我从别处获取了这种格式的数据。 我想从这里实现的是将这个列表列表转换为字典,以便我可以传递与我for
循环相关的正确参数。 到目前为止,这是我所在的位置:
geos_dict = {geo[0]:None for geo in geos}
for i, geos_dict in enumerate(geos_dict):
options = ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(service=Service('/Library/path/chromedriver'))
driver.execute_cdp_cmd("Browser.grantPermissions", {"origin":
"https://www.google.com","permissions": ["geolocation"]})
#This is the line where the error is occurring
driver.execute_cdp_cmd("Emulation.setGeolocationOverride",
{"latitude": geo["latitude"], "longitude":
geo["longitude"], "accuracy": geo["accuracy"]})
driver.get("https://www.google.com")
我返回一个错误: TypeError: list indices must be integers or slice, not str
显然,我这样做不对。 但是我对将列表转换为字典以及从键:值对调用值知之甚少。
我怎样才能做到这一点?
列表中的每个元素都是一个单元素列表,而该单元素是一个字符串。 该字符串代表一个字典,减去左花括号和右花括号。 ast.literal_eval
提供了一种安全的方法来解析这样的文字数据结构。
另外:你说你想将geos
转换成字典,你的代码也是这样做的,但你真正想要的是一个字典列表,然后循环。
from ast import literal_eval
from pprint import pprint
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"]]
geos = [literal_eval(f'{{{geo[0]}}}') for geo in geos]
pprint(geos, sort_dicts=False)
Output(使用pprint
更容易看到嵌套结构):
[{'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}]
顺便说一句,那是格式化的字符串文字或"f-string" 。 您可以使用{}
在此类字符串中包含变量或其他表达式,并且可以转义,即使用{{
{
所以 f-string 所做的就是将{}
放在每个字符串周围,使其成为字典的有效表示。
可能有点慢,但你想要这样的东西
import re
parser = re.compile("'latitude': (.*), 'longitude': (.*), 'accuracy': (.*)")
for geo in geos:
match = parser.match(geo[0])
# in match object will be 3 groups
lat, long, acc = match.groups()
geo_dict = {'latitude': lat, 'longitude': long, 'accuracy' : acc}
... #
driver.execute_cdp_cmd("Emulation.setGeolocationOverride", geo_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.