从API返回的列表中获取价值

时间:2019-07-29 06:06:04

标签: python list api

我正在努力从API调用返回的列表中提取特定值。这是列表(缩短版本):

[{'account': 231584,'simpleCost': 0.0, 'simpleValue': 0.0, 'avgEntryPrice': 0.0, ...}]

,并返回:

client.Position.Position_get(filter=json.dumps({'symbol': 'XBTUSD'})).result()

我希望将“ avgEntryPrice”提取为变量,谢谢大家!

1 个答案:

答案 0 :(得分:2)

您将达到这样的值:

list = [{'account': 231584,'simpleCost': 0.0, 'simpleValue': 0.0, 'avgEntryPrice': 0.0, ...}]
list[0]["avgEntryPrice"]

因为列表仅将字典作为其项。因此,您需要访问列表的第一项,然后使用该字典中的键访问所需的值。

如果您有多个词典,可以这样做:

list = [{'account': 231584,'simpleCost': 0.0, 'simpleValue': 0.0, 'avgEntryPrice': 0.0}, {'account': 231584,'simpleCost': 0.0, 'simpleValue': 0.0, 'avgEntryPrice': 0.0}, {'account': 231584,'simpleCost': 0.0, 'simpleValue': 0.0, 'avgEntryPrice': 0.0}, {'account': 231584,'simpleCost': 0.0, 'simpleValue': 0.0, 'avgEntryPrice': 0.0}]
avgEntryPrices = [item["avgEntryPrice"] for item in list]

这将返回列表中每个字典的 avgEntryPrice