【发布时间】:2021-06-28 21:13:24
【问题描述】:
我是使用 Google 距离矩阵 API 的新手,我不断收到以下错误“KeyError: 'distance'”,而不是距离值。类似问题的所有解决方案似乎都符合我正在使用的代码,其中列表“行”和“元素”中的第一项使用索引 [0] 访问,然后是“距离”和“值”项像字典一样访问。
以下是相关代码块:
# Loop through each row in the data frame using pairwise for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
#Assign latitude and longitude as origin/departure points
LatOrigin = row1["latitude"]
LongOrigin = row1["longitude"]
origins = (LatOrigin,LongOrigin)
#Assign latitude and longitude from the next row as the destination point
LatDest = row2["latitude"] # Save value as lat
LongDest = row2["longitude"] # Save value as lat
destination = (LatDest,LongDest)
#pass origin and destination variables to distance_matrix function# output in meters
result = gmaps.distance_matrix(origins, destination, mode='walking')["rows"][0]["elements"][0]['distance']["value"]
#append result to list
list.append(result)
这是我期望的 JSON 有效负载的格式:
{
"originAddresses": [ "Greenwich, Greater London, UK", "13 Great Carleton Square, Edinburgh, City of Edinburgh EH16 4, UK" ],
"destinationAddresses": [ "Stockholm County, Sweden", "Dlouhá 609/2, 110 00 Praha-Staré Město, Česká republika" ],
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 70778,
"text": "19 hours 40 mins"
},
"distance": {
"value": 1887508,
"text": "1173 mi"
}
}, {
"status": "OK",
"duration": {
"value": 44476,
"text": "12 hours 21 mins"
},
"distance": {
"value": 1262780,
"text": "785 mi"
}
} ]
}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 96000,
"text": "1 day 3 hours"
},
"distance": {
"value": 2566737,
"text": "1595 mi"
}
}, {
"status": "OK",
"duration": {
"value": 69698,
"text": "19 hours 22 mins"
},
"distance": {
"value": 1942009,
"text": "1207 mi"
}
} ]
} ]
}
【问题讨论】:
-
似乎“元素”的元素[0]没有键“距离”。如果您尝试使用
["rows"][0]["elements"][1]['distance']["value"],是否会收到相同的错误消息? -
@KevinQuinzel,谢谢。试过了,但得到了 IndexError: list index out of range
-
我的错。刚刚注意到“距离”是用简单的引号写的。用双引号 ["distance"] 得到相同的结果吗
-
凯文,很好,但存在这种差异是因为我在解决问题时使用了引号。双引号问题仍然存在。
标签: python json google-maps google-distancematrix-api python-jsons