【问题标题】:How do I access a value from a dictionary within a dictionary that is a string如何从作为字符串的字典中的字典中访问值
【发布时间】:2018-01-19 03:42:30
【问题描述】:

我一直在为计算机科学 30 门课程做作业。在这个作业中,我被要求访问一个 API 并返回一个特定的值,而不仅仅是整个字典。我的问题是我似乎无法打印我想要的值,因为它是一个字符串而不是整数或切片。如果您决定向我提供帮助,这是我为您提供的完整代码。感谢您的宝贵时间。

import requests
import urllib.parse

# set up a temporary copy of the google api
temp = "https://maps.googleapis.com/maps/api/directions/json?
origin=Disneyland&destination=Universal+Studios+Hollywood4"

# set up the main API and the origin and destination inputs from the user
main_api = "https://maps.googleapis.com/maps/api/directions/json?"
origin = str(input("Enter in the place that is you are going away from: "))
destination = str(input("Enter the destination that you would like to reach: 
"))

# set up the url from the main api, the origin, and the destination
url = main_api + urllib.parse.urlencode({"origin": origin, "destination": 
destination})
# print the url back to the user
print(url)

# show the user the distance between the origin and the destination
json_data = requests.get(url).json()
print(json_data['routes']['legs']['distance']['text'])

【问题讨论】:

标签: python api dictionary


【解决方案1】:

您有几个嵌套在 json dict 响应中的列表。看看下面的结果!

json_data['routes'][0]['legs'][0]['distance']

输出

{'text': '1,153 mi', 'value': 1855409}

【讨论】:

  • 谢谢!那行得通!这对我帮助很大。你能告诉我为什么这行得通吗?我想从中学习。
  • 在处理 API 时,这是一种非常常见的模式,尤其是在处理大量数据时。我弄清楚如何获得正确级别或索引的方法是:调用 json_data.keys(),检查 dict 的键,找到我需要的键,然后查看它。您可能会看到它是一个列表,其中包含字典,然后调用 json_data['mykey'][0].keys(),然后检查您还需要提取哪些键。我想说几乎所有我使用过的 API 都遵循这种模式,至少来自 Google。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
相关资源
最近更新 更多