Omeed Totakhel Omeed Totakhel - 6 months ago 12
Python Question

get the values of dictionary out of list python

I am using googelmaps library to measure distance between two points. here is it's out put. does any one 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()

Answer

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'