【问题标题】:Retrieving a value inside a python dictionary, that is inside a dictionary检索python字典中的值,即字典中的值
【发布时间】:2021-03-11 22:44:03
【问题描述】:

我将以下 json 转换为字典。现在我想将 href 值保存到一个变量中。

{
 "request_id":"9838-25be1f8e6e57",
 "message":"Validation request submitted.",
 "links":[
   {
     "href":"/v1/app/validate/status/9838-25be1f8e6e57",
     "rel":"status"
    },
    {
     "href":"/v1/app/report/9838-25be1f8e6e57",
     "rel":"report"
    }
 ]
}

apiLinks=dict(response.json())
for links in apiLinks['links']:
     print(links['href'])

以下代码确实单独打印出 href 值,但我想知道如何访问它们,以便将它们存储到变量中。我知道 python 中的字典有一个 .get 函数,但我似乎无法正确。

谢谢

【问题讨论】:

  • href_list = [elem['href'] for elem in response.json['links']]

标签: json python-3.x api dictionary


【解决方案1】:

创建一个列表并将值附加到该列表而不是打印它们:

links_list = []
for links in apiLinks['links']:
    link_list.append(links['href'])

见:https://docs.python.org/3/tutorial/introduction.html#lists

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    相关资源
    最近更新 更多