1

So I was trying to grab information about the distance between two cities and save the results in a variable

distance_result_dic = gmaps.distance_matrix("Sydney Town Hall",
                                 "Parramatta, NSW",
                                 mode="transit",
                                 departure_time=now)

The result of print(distance_result_dic) is:

{
  'destination_addresses': ['Parramatta NSW 2150, Australia'],
  'origin_addresses': ['483 George St, Sydney NSW 2000, Australia'],
  'rows': [{
        'elements': [{
            'distance': {'text': '24.4 km', 'value': 24414}, 
            'duration': {'text': '44 mins', 'value': 2665}, 
            'status': 'OK'
        }]
  }],
  'status': 'OK'
}

Then I would like to access a certain value like 'value' so that i can save the 24414 in another Variable. I tried this:

distance_value = distance_result_dic['rows']['elements']['distance']['value']

But I get the following error message:

list indices must be integers or slices, not str

which indicates that the dictionary-element 'rows' contains a list. Yet I don't know how to access that list and its elements from the dictionary distance_result_dic directly

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
Kloud
  • 101
  • 2
  • 7
  • 1
    `distance_result_dic['rows'][0]['elements'][0]['distance']['value']`. It's clear in the string that you posted that several of the keys have lists associated with them, and the dictionary is contained within that list, so you need to use list indices to get at the dictionaries inside. – roganjosh Dec 04 '17 at 16:24
  • Possible duplicate of [Python Accessing Nested JSON Data](https://stackoverflow.com/questions/23306653/python-accessing-nested-json-data) – roganjosh Dec 04 '17 at 16:26
  • Thank you so much, solved my problem ! – Kloud Dec 04 '17 at 16:33

0 Answers0