简体   繁体   English

检索特定字典值 - Python

[英]Retrieving specific dictionary value - Python

Sorry guys this is a very newbie question. 对不起,这是一个非常新手的问题。 I currently have the following code 我目前有以下代码

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)

the print out is the the following 打印输出如下

{'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']} {'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']}

I ultimately want to extract the result 0.9km. 我最终想要提取0.9km的结果。 How do I do that? 我怎么做?

I have tried using 我试过用

print(my_distance['rows']) 

and that only gives me 这只会给我

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

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

I then get an error 然后我得到一个错误

TypeError: list indices must be integers or slices, not str TypeError:list indices必须是整数或切片,而不是str

any help would be much appreciated thanks! 任何帮助将不胜感激,谢谢!

elements and rows is are list of dictionaries, not a dictionary themselves. elementsrows是字典列表,而不是字典本身。 Access them like this: 像这样访问它们:

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'

dictionary is {key:value}, list in python is [elementA, elmentB] , therefore for dict2 = {key:[{key:value}]} you have to use dict2['key'][0] to get the inner {key:value} 字典是{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