簡體   English   中英

檢索特定字典值 - Python

[英]Retrieving specific dictionary value - Python

對不起,這是一個非常新手的問題。 我目前有以下代碼

import googlemaps
import json as js
from datetime import datetime

gmaps = googlemaps.Client(key=googleapikey)
my_distance = gmaps.distance_matrix('350 5th Ave, New York, NY 10118',
                                '4 Pennsylvania Plaza, New York, NY 10001')
print(my_distance)

打印輸出如下

{'status':'OK','rows':[{'elements':[{'distance':{'value':876,'text':'0.9 km'},'duration':{'value' :324,'text':'5分鍾'},'狀態':'確定'}]}},'destination_addresses':['4賓夕法尼亞廣場,紐約,紐約10001,美國'],'origin_addresses':[ '350 5th Ave,New York,NY 10118,USA']}

我最終想要提取0.9km的結果。 我怎么做?

我試過用

print(my_distance['rows']) 

這只會給我

[{'elements':[{'status':'OK','distance':{'value':876,'text':'0.9 km'},'duration':{'value':324,'text ':'5分鍾'}}]}]

print(my_distance['rows']['elements']['distance'])

然后我得到一個錯誤

TypeError:list indices必須是整數或切片,而不是str

任何幫助將不勝感激,謝謝!

elementsrows是字典列表,而不是字典本身。 像這樣訪問它們:

print(my_distance['rows'][0]['elements'][0]['distance'])
>>> mydict = {'status': 'OK', 'rows': [{'elements': [{'distance': {'value': 876, 'text': '0.9 km'}, 'duration': {'value': 324, 'text': '5 mins'}, 'status': 'OK'}]}], 'destination_addresses': ['4 Pennsylvania Plaza, New York, NY 10001, USA'], 'origin_addresses': ['350 5th Ave, New York, NY 10118, USA']}
>>> mydict['rows'][0]['elements'][0]['distance']['text']
    '0.9 km'

字典是{key:value},python中的list是[elementA, elmentB] ,因此對於dict2 = {key:[{key:value}]}你必須使用dict2 ['key'] [0]來獲得內在的{key:value}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM