drsalt drsalt - 1 month ago 7
Python Question

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!

Ray Ray
Answer

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

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