drsalt
drsalt

Reputation: 117

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

I ultimately want to extract the result 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'}}]}]

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

I then get an error

TypeError: list indices must be integers or slices, not str

any help would be much appreciated thanks!

Upvotes: 1

Views: 60

Answers (2)

Ray
Ray

Reputation: 41448

elements and rows is are list of dictionaries, not a dictionary themselves. Access them like this:

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

Upvotes: 0

Haifeng Zhang
Haifeng Zhang

Reputation: 31905

>>> 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}

Upvotes: 0

Related Questions