Omeed Totakhel
Omeed Totakhel

Reputation: 487

get the values of dictionary out of list python

I am using the googlemaps library to measure distance between two points. Here is its output. Does anyone know how to assign the distance ('text': '1,271km') to variable?

dic = {'rows': [{'elements': [{'distance': {'value': 1271380,
                                            'text': '1,271 km'},
                               'duration': {'value': 43350,
                                            'text': '12 hours 3 mins'},
                               'status': 'OK'}]}],
       'status': 'OK',
       'destination_addresses': ['New York, NY, USA'],
       'origin_addresses': ['Chicago, IL, USA']}

Example:

for x in dic:
     if x == 'distance':
         var = x.values()

Upvotes: 0

Views: 76

Answers (2)

Rahul K P
Rahul K P

Reputation: 16081

In [1]: distance = dic['rows'][0]['elements'][0]['distance']['text']
In [2]: distance
Out[1]: '1,271 km'
In [3]: duration = dic['rows'][0]['elements'][0]['duration']['text']
In [4]: duration
Out[2]: '12 hours 3 mins'

Use like this. But this is particularly for this dict

Upvotes: 0

DevLounge
DevLounge

Reputation: 8447

I assume that you posted only 1 row and 1 element, but your data might have more than this.

This is how you can iterate and extract the distance value, for example:

>>> for row in dic['rows']:
...   for element in row['elements']:
...     text = element['distance']['text']
... 
>>> text
'1,271 km'

Upvotes: 1

Related Questions