我想从字典中的列表中获取值。当我发出Oanda REST-API请求时,我得到以下json数据结构。
当我使用get函数时,我可以从“trades”和“lastTransactionID”访问dict及其键及其值,但不知道如何获取“trades”键中的列表项。
如果你能帮助我实现这个目标,我将非常感激
作品 print rv.get(“trades”)
不起作用 print rv.get(“trades”)。get(“financing”)
{
"trades": [
{
"financing": "0.0000",
"openTime": "2017-11-08T17:21:49.533679739Z",
"price": "1.15901",
"unrealizedPL": "-0.0001",
"realizedPL": "0.0000",
"instrument": "EUR_USD",
"state": "OPEN",
"initialUnits": "1",
"currentUnits": "1",
"id": "2046"
},
{
"financing": "0.0000",
"openTime": "2017-11-08T17:19:27.343697147Z",
"price": "1.15905",
"unrealizedPL": "-0.0001",
"realizedPL": "0.0000",
"instrument": "EUR_USD",
"state": "OPEN",
"initialUnits": "1",
"currentUnits": "1",
"id": "2044"
}
],
"lastTransactionID": "2046"
}
感谢您的帮助和亲切的问候
答案 0 :(得分:2)
只需遍历列表:
for trade in rv.get("trades"):
print trade.get("financing")
print rv.get("trades").get("financing")
不起作用,因为rv.get("trades")
会返回词典列表。这些词典是带有"financing"
键的词典。
答案 1 :(得分:0)
你只需要遍历列表:
演示here
data = {
"trades": [
{
"financing": "0.0000",
"openTime": "2017-11-08T17:21:49.533679739Z",
"price": "1.15901",
"unrealizedPL": "-0.0001",
"realizedPL": "0.0000",
"instrument": "EUR_USD",
"state": "OPEN",
"initialUnits": "1",
"currentUnits": "1",
"id": "2046"
},
{
"financing": "0.0000",
"openTime": "2017-11-08T17:19:27.343697147Z",
"price": "1.15905",
"unrealizedPL": "-0.0001",
"realizedPL": "0.0000",
"instrument": "EUR_USD",
"state": "OPEN",
"initialUnits": "1",
"currentUnits": "1",
"id": "2044"
}
],
"lastTransactionID": "2046"
};
for d in data['trades']:
print(d['openTime'])
返回:
2017-11-08T17:21:49.533679739Z
2017-11-08T17:19:27.343697147Z
答案 2 :(得分:0)
rv.get("trades").get("financing")
无效,因为trades
值不是字典而是列表。您可以通过执行type(rv.get('trades'))
来检查其类型。所以正确的方法是
rv.get("trades")[0].get("financing")
rv.get("trades")[1].get("financing")
所以你需要迭代列表
for item in rv.get('trades'):
print(item.get('financing'))
答案 3 :(得分:0)
另一个简洁的选择是使用列表理解,这将允许单行解决方案:
[trade.get("financing") for trade in rv.get("trades")]
请注意,这并不比@Bahrom更好,在我看来只是更加pythonic。