YoYo YoYo - 3 months ago 8
Python Question

Getting multiple values in dictionary

I want to get the values of a key in a dictionary. After working with googlemaps and I got my result, I want to just get the values I need and move on. But it seems not to be working for me.

The result:

>>>the_distance= gmaps.distance_matrix(origins, destinations)
>>> print the_distance
{u'status': u'OK', u'rows': [{u'elements': [{u'duration': {u'text': u'27 mins', u'value': 1599}, u'distance': {u'text': u'11.9 km', u'value': 11874}, u'status': u'OK'}]}], u'origin_addresses': [u'Lamu, Kayyy'], u'destination_addresses': [u'20 Dave Ave, Mars, Amsterdam']}


Looking at the result, the key 'rows' has different values. I only need the duration:
27 mins
and distance:
11.9km
.

I tried

>>>the_distance.values()[1:3]


I got the same result as above.

I also tried

>>the_distance['rows'][:2]


I got

{u'status': u'OK', u'rows': [{u'elements': [{u'duration': {u'text': u'27 mins', u'value': 1599}, u'distance': {u'text': u'11.9 km', u'value': 11874}, u'status': u'OK'}]}]


what do I need to do?

Answer

simple access to the dictionary could be done as follows.

cool_variable = the_distance['rows'][0]['elements'][0]
cool_variable['duration']['text']
cool_variable['distance']['text']
Comments