简体   繁体   English

过滤 python 请求结果

[英]filter python requests result

I am new to Python and am using requests to extract data from an API and now I want to sum only certain values from the output:我是 Python 的新手,我正在使用请求从 API 中提取数据,现在我只想对 output 中的某些值求和:

import requests
import json

url = "APIlink"

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

When I print output I get a result looking like this:当我打印 output 时,我得到的结果如下所示:

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

How can I filter only the capacity?如何仅过滤容量? And how can I sum all the capacity to 36?我怎样才能将所有容量加起来为 36?

I tried something like print(output[0].capacity) to test how I would do this, but then I get the following:我尝试了类似 print(output[0].capacity) 的方法来测试我将如何执行此操作,但随后我得到以下信息:

AttributeError: 'dict' object has no attribute 'capacity' Does this mean that it is still no JSON output? AttributeError: 'dict' object has no attribute 'capacity' 这是否意味着它仍然没有 JSON output?

I am probably missing something really basic...我可能错过了一些非常基本的东西......

After getting data from API you can do anything you want.从 API 获取数据后,您可以做任何您想做的事情。

For example, you can sum capacity with list comprehension.例如,您可以将容量与列表理解相加。

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

Or filter it like this或者像这样过滤

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

Pay attention, that you got list in your output.请注意,您的 output 中有列表。

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

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

Dicts have keys, you can reference them in squarebrackets!( ["capacity"] ) Also, this is a list, so you have to write [0] to get the element of the list.字典有键,你可以在方括号中引用它们!( ["capacity"] )另外,这是一个列表,所以你必须写[0]来获取列表的元素。

You have a list of dictionaries.你有一个字典列表。 Among other solutions, you could use在其他解决方案中,您可以使用

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

Dict keys are indexed using [] , so for example:字典键使用[]进行索引,例如:

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

Will print the number 69将打印数字 69

Quick and easy way to sum all capacities, in your case, with a comprehension:在您的情况下,快速简便地总结所有能力,并理解:

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

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

Total is 36总数为 36

Side note/tip, use dict.get() instead of dict[] to rather have None returned instead of an index error, for example:旁注/提示,使用dict.get()而不是dict[]宁愿返回None而不是索引错误,例如:

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

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

this is a list of dictionaries.这是一个字典列表。 item is a dictionary with key value pair. item 是具有键值对的字典。

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

output: output:

5,31

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM