筛选 python 请求结果

filter python requests result

我是 Python 的新手,我正在使用请求从 API 中提取数据,现在我只想对输出中的某些值求和:

import requests
import json

url = "APIlink"

payload={}
headers = {
  'Authorization': 'Bearer '+accesstoken
}
response = requests.request("GET", url, headers=headers, data=payload)
output = response.json()

当我打印输出时,我得到的结果如下所示:

[{'id': 1, 'capacity': 5}, {'id': 2, 'capacity': 31}]

如何只筛选容量? 以及如何将所有容量加起来为 36?

我尝试了类似 print(output[0].capacity) 的方法来测试我将如何执行此操作,但随后我得到以下信息:

AttributeError: 'dict' 对象没有属性 'capacity' 这是否意味着它仍然没有 JSON 输出?

我可能遗漏了一些非常基本的东西...

json = [{'id': 1, 'capacity': 5}, {'id': 2, 'capacity': 31}]

print(json[0]["capacity"])

字典有键,你可以在方括号中引用它们!(["capacity"])另外,这是一个列表,所以你必须写[0]来获取列表的元素。

从 API 获取数据后,您可以做任何您想做的事情。

例如,您可以使用列表推导求和容量。

capacity = sum([x['capacity'] for x in output])

或者像这样过滤

filtered =  list(filter(lambda x: x['id'] ==1, output))

注意,你的输出中有列表。

您有一个字典列表。在其他解决方案中,您可以使用

result = sum([x['capacity'] for x in output])

字典键使用 [] 索引,例如:

foo = {"bar": 69}
print(foo["bar"])

将打印数字 69

在您的情况下,通过理解来快速简便地总结所有能力:

output = [{'id': 1, 'capacity': 5}, {'id': 2, 'capacity': 31}

total = sum(dictionary["capacity"] for dictionary in output)

总数是 36

端 note/tip,使用 dict.get() 而不是 dict[] 而 [=返回 14=] 而不是索引错误,例如:

# This will throw a KeyError
dictionary = {"foo": 69}
x = dictionary["baz"]

# This will return None
x = dictionary.get("baz")

这是字典列表。 item 是一个带有键值对的字典。

my_dict = [{'id': 1, 'capacity': 5}, {'id': 2, 'capacity': 31}]
for item in my_dict:
    print(item['capacity'])

输出:

5,31