drsalt drsalt - 9 months ago 70
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')

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


and that only gives me

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


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 Source

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