[英]How to extract a specific value from a dictionary in python
I want to extract distance from google distance matrix API in Python. 我想从Python中的Google距离矩阵API中提取距离。 The objet it returned is a python dictionary. 它返回的对象是python字典。
{
'destination_addresses': [Mumbai, Maharashtra, India '],
'origin_addresses': ['Powai, Mumbai, Maharashtra, India'],
'rows': [{
'elements': [{
'distance': {
'text': u '47.1 km',
'value': 47086
},
'duration': {
'text': '1 hour 17 mins',
'value': 4628
},
'status': 'OK'
}]
}],
'status': 'OK'
}
I want to extract the distance and duration from above. 我想从上方提取距离和持续时间。 I have used 我用过
distance = my_distance["rows"]
for a in distance:
result = a["elements"]
print result
It gave me 它给了我
[{
u 'duration': {
u 'text': u '1 hour 17 mins', u 'value': 4628
}, u 'distance': {
u 'text': u '47.1 km', u 'value': 47086
}, u 'status': u 'OK'
}]
Now how to extract duration (1 hour 17 mins) and distance (47.1 km) and their corresponding values (4628 & 47086) 现在如何提取持续时间(1小时17分钟)和距离(47.1公里)及其对应的值(4628和47086)
You may simply do it as: 您可以简单地这样做:
print "time taken : ", d["rows"][0]["elements"][0]["duration"]["text"]
print "distance : ", d["rows"][0]["elements"][0]["distance"]["text"]
print "distance value : ", d["rows"][0]["elements"][0]["distance"]["value"]
print "duration value : ", d["rows"][0]["elements"][0]["duration"]["value"]
a["elements"]
contains a list of dictionaries. a["elements"]
包含字典列表。 You can either iterate over it or fetch values by the index value. 您可以对其进行迭代,也可以按索引值获取值。 You can try this in the for
loop: 您可以在for
循环中尝试以下操作:
distance = result[0]['text']
duration = result[1]['text']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.