从 API 响应列表中获取数据
Get data from list of API response
price_list = [{'symbol': 'ETHBTC', 'lastPrice': '0.03574700'}, {'symbol': 'BTCUSDT', 'lastPrice': '57621.08000000'}]
print(price_list[1]['lastPrice']) # index = 1 for BTCUSDT, print 57621.08000000 => OK.
我需要获取 BTCUSDT 的最后价格。
目前我可以通过索引获取它。
但是,是否可以通过引用符号来获取它?
鉴于您只有两个键,它们等于 identifier
和 value
。
您可以创建一个 dict
并将您的 price_list
扁平化为 symbol
的键值对:lastPrice
从而更容易通过以下方式访问您需要的价格dict[symbol]
data = {k['symbol']: float(k['lastPrice']) for k in price_list}
data
#{'ETHBTC': 0.035747, 'BTCUSDT': 57621.08}
data['BTCUSDT']
#57621.08
price_list = [{'symbol': 'ETHBTC', 'lastPrice': '0.03574700'}, {'symbol': 'BTCUSDT', 'lastPrice': '57621.08000000'}]
print(price_list[1]['lastPrice']) # index = 1 for BTCUSDT, print 57621.08000000 => OK.
我需要获取 BTCUSDT 的最后价格。
目前我可以通过索引获取它。
但是,是否可以通过引用符号来获取它?
鉴于您只有两个键,它们等于 identifier
和 value
。
您可以创建一个 dict
并将您的 price_list
扁平化为 symbol
的键值对:lastPrice
从而更容易通过以下方式访问您需要的价格dict[symbol]
data = {k['symbol']: float(k['lastPrice']) for k in price_list}
data
#{'ETHBTC': 0.035747, 'BTCUSDT': 57621.08}
data['BTCUSDT']
#57621.08