将从REST api检索的数据存储到python中的变量中

时间:2014-09-19 22:09:31

标签: python json python-requests

所以我正在尝试更多地了解API以及我可以使用它们的不同方法。说现在我已经

import requests, json, pprint

r = requests.get("values from api") 

pprint.pprint(r.json())

返回给我以下

> {'currentResultCount': '10',  
> 'results': [{'Name': 'Item_One',
>               'Price': '464086'},
>              {'Name': 'Item_Two',
>               'Price': '70874',
>                and so on.........

如果我想将所有价格存储在一个数组中并对它们进行一些数据分析(比如查找均值,中位数和模式),我该怎么办?

我尝试调用r [0]来查看它是否有效,但是显然r是一个响应对象类型,因此r [0]不起作用。这是我第一次学习API和数据操作,非常感谢任何建议和学习技巧!

2 个答案:

答案 0 :(得分:2)

.json()解析JSON响应并返回一个Python数据结构,在您的情况下,常规dictionary

data = r.json()

要获取价格列表,请迭代results值并在每次迭代时获得Price

prices = [item['Price'] for item in data['results']]

您也可以将价格转换为float

prices = [float(item['Price']) for item in data['results']]

答案 1 :(得分:1)

此处rResponse类型对象,其中包含服务器对HTTP请求的响应。现在在你正在使用的代码中,

r = requests.get("values from api")

get方法必须收到url作为参数。

您可以使用dir(r)查看对象的属性。你可以试试其中一些。如果有响应的json编码内容,r.json()将返回它。现在josn与python dictionary非常相似。因此,您可以将其用作字典,将其存储在列表中并操作数据。