Reputation: 13
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...
Upvotes: 0
Views: 2884
Reputation: 4253
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
Upvotes: 0
Reputation:
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")
Upvotes: 0
Reputation: 491
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.
Upvotes: 2
Reputation: 43189
You have a list of dictionaries. Among other solutions, you could use
result = sum([x['capacity'] for x in output])
Upvotes: 0
Reputation: 122
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.
Upvotes: 1