从嵌套字典中提取信息(google 映射 distance_matrix)

Extract information from nested dictionary (google maps distance_matrix)

如何从这个嵌套字典中仅获取“距离”和“持续时间”以仅包含以下值:6.1 公里和 21 分钟?我尝试了 .get 函数,但得到的是“0”输出。

my_distance = gmaps.distance_matrix('Empire State','10031')

my_distance

{'destination_addresses': ['New York, NY 10026, USA'], 'origin_addresses': ['Manhattan, NY 10036, USA'], 'rows': [{'elements': [{'distance': {'text': '6.1 km', 'value': 6138}, 'duration': {'text': '21 mins', 'value': 1257}, 'status': 'OK'}]}], 'status': 'OK'}
{'destination_addresses': ['New York, NY 10031, USA'], 'origin_addresses': ['Manhattan, NY 10036, USA'], 'rows': [{'elements': [{'distance': {'text': '10.3 km', 'value': 10314}, 'duration': {'text': '20 mins', 'value': 1176}, 'status': 'OK'}]}], 'status': 'OK'}
{'destination_addresses': ['New York, NY 10032, USA'], 'origin_addresses': ['Manhattan, NY 10036, USA'], 'rows': [{'elements': [{'distance': {'text': '12.0 km', 'value': 12015}, 'duration': {'text': '17 mins', 'value': 1034}, 'status': 'OK'}]}], 'status': 'OK'}


my_distance
test=my_distance.get('distance',0)
test

0

你需要多次索引字典来获取这些值,因为它们嵌套在多层中。例如,要获取距离,使用:

my_distance["rows"][0]["elements"][0]["distance"]["text"]

这是获取两个值的完整代码:

my_distance = {'destination_addresses': ['New York, NY 10026, USA'], 'origin_addresses': ['Manhattan, NY 10036, USA'], 'rows': [{'elements': [{'distance': {'text': '6.1 km', 'value': 6138}, 'duration': {'text': '21 mins', 'value': 1257}, 'status': 'OK'}]}], 'status': 'OK'}

values = ["distance", "duration"]

results = []
for v in values:
    results.append(my_distance["rows"][0]["elements"][0][v]["text"])

for v, r in zip(values, results):
    print(f"{v}: {r}")

这会打印:

distance: 6.1 km
duration: 21 mins