简体   繁体   中英

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:

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:

[{'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?

I tried something like print(output[0].capacity) to test how I would do this, but then I get the following:

AttributeError: 'dict' object has no attribute 'capacity' Does this mean that it is still no JSON output?

I am probably missing something really basic...

After getting data from API you can do anything you want.

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.

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.

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

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

Side note/tip, use dict.get() instead of dict[] to rather have None returned instead of an index error, for example:

# 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.

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

output:

5,31

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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