Omeed Totakhel Omeed Totakhel - 8 months ago 20
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']}


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


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'