【问题标题】:python 3 get specific value from json dictionarypython 3从json字典中获取特定值
【发布时间】:2018-09-01 17:47:21
【问题描述】:

我有一本从 API 调用中获取的字典。我正在尝试从结果中获取特定值。

names = requests.get("http://some.api")

打印时调用的结果如下所示

{'mynames': [{'id': 38, 'name': 'Betsy'}, {'id': 93, 'name': 'Pitbull'}, {'id': 84, 'name': 'Liberty'}]}

我尝试了下面的代码,只是为了获取以“Pitbull”为名称的结果

filtered_names = {k:v for (k,v) in names.items() if "Pitbull" in v}

我得到一个错误

AttributeError: 'Response' object has no attribute 'items'

如何从 API 调用中提取的数据中获取特定值?

【问题讨论】:

    标签: python python-3.x dictionary python-requests


    【解决方案1】:

    requests.get 给出一个'Response' 对象而不是dict。只有后者有items的迭代方法。

    您可以使用json 库来检索常规 Python 字典:

    import json
    import requests
    
    names = requests.get("http://some.api")
    d = json.loads(names.text)
    

    然后请注意,您有一个带有一个键的字典,其中的值是字典列表。因此,您需要访问 d['mynames'] 以通过 list 理解检索范围内的字典。

    filtered_names = [el for el in d['mynames'] if 'Pitbull' in el['name']]
    
    # [{'id': 93, 'name': 'Pitbull'}]
    

    【讨论】:

    • 你对names.text有什么看法?
    • 如果我只是使用 for k 打印 k,d.items() 中的 v 只会打印 'mynames'
    • 谢谢,现在明白了
    【解决方案2】:
    import json
    names = requests.get('https://api')
    Json = json.loads(names)
    
    filtered_names = {k:v for k,v in Json.items() if "Pitbull" in v}
    

    现在我们脑海中的一个问题必须是这个 json.py 是做什么的? 这个问题的答案你可以参考enter link description here

    希望这不会引发AttributeError

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2022-01-25
      • 2019-04-19
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 2016-11-20
      • 2017-01-05
      相关资源
      最近更新 更多