[英]Finding specific dict in a long list of dicts
嗨,我正在使用 api 来响应很长的字典列表。 我正在尝试根据输入的参数查找并解析其中的一个特定参数。
以下是其中一个外观的示例(响应)。
{'symbol': 'XBTUSD', 'rootSymbol': 'XBT', 'state': 'Open', 'typ': 'FFWCSX', 'listing': '2016-05-13T12:00:00.000Z', 'front': '2016-05-13T12:00:00.000Z', 'expiry': None, 'settle': None, 'relistInterval': None, 'inverseLeg': '', 'sellLeg': '', 'buyLeg': '', 'optionStrikePcnt': None, 'optionStrikeRound': None, 'optionStrikePrice': None, 'optionMultiplier': None, 'positionCurrency': 'USD', 'underlying': 'XBT', 'quoteCurrency': 'USD', 'underlyingSymbol': 'XBT=', 'reference': 'BMEX', 'referenceSymbol': '.BXBT', 'calcInterval': None, 'publishInterval': None, 'publishTime': None, 'maxOrderQty': 10000000, 'maxPrice': 1000000, 'lotSize': 1, 'tickSize': 0.5, 'multiplier': -100000000, 'settlCurrency': 'XBt', 'underlyingToPositionMultiplier': None, 'underlyingToSettleMultiplier': -100000000, 'quoteToSettleMultiplier': None, 'isQuanto': False, 'isInverse': True, 'initMargin': 0.01, 'maintMargin': 0.005, 'riskLimit': 20000000000, 'riskStep': 10000000000, 'limit': None, 'capped': False, 'taxed': True, 'deleverage': True, 'makerFee': -0.00025, 'takerFee': 0.00075, 'settlementFee': 0, 'insuranceFee': 0, 'fundingBaseSymbol': '.XBTBON8H', 'fundingQuoteSymbol': '.USDBON8H', 'fundingPremiumSymbol': '.XBTUSDPI8H', 'fundingTimestamp': '2019-10-06T20:00:00.000Z', 'fundingInterval': '2000-01-01T08:00:00.000Z', 'fundingRate': 1.8e-05, 'indicativeFundingRate': 0.0001, 'rebalanceTimestamp': None, 'rebalanceInterval': None, 'openingTimestamp': '2019-10-06T15:00:00.000Z', 'closingTimestamp': '2019-10-06T16:00:00.000Z', 'sessionInterval': '2000-01-01T01:00:00.000Z', 'prevClosePrice': 7958.87, 'limitDownPrice': None, 'limitUpPrice': None, 'bankruptLimitDownPrice': None, 'bankruptLimitUpPrice': None, 'prevTotalVolume': 1728502232271, 'totalVolume': 1728646525355, 'volume': 144293084, 'volume24h': 1782133095, 'prevTotalTurnover': 24621093055851532, 'totalTurnover': 24622900293319236, 'turnover': 1807237467704, 'turnover24h': 22217259191678, 'homeNotional24h': 222172.5919167777, 'foreignNotional24h': 1782133095, 'prevPrice24h': 8046, 'vwap': 8021.8193, 'highPrice': 8200, 'lowPrice': 7864.5, 'lastPrice': 8017.5, 'lastPriceProtected': 8011.5366, 'lastTickDirection': 'ZeroPlusTick', 'lastChangePcnt': -0.0035, 'bidPrice': 8010.5, 'midPrice': 8010.75, 'askPrice': 8011, 'impactBidPrice': 8010.2531, 'impactMidPrice': 8011, 'impactAskPrice': 8011.5366, 'hasLiquidity': True, 'openInterest': 775122347, 'openValue': 9666550789437, 'fairMethod': 'FundingRate', 'fairBasisRate': 0.019710000000000002, 'fairBasis': 0.08, 'fairPrice': 8018.77, 'markMethod': 'FairPrice', 'markPrice': 8018.77, 'indicativeTaxRate': 0, 'indicativeSettlePrice': 8018.69, 'optionUnderlyingPrice': None, 'settledPrice': None, 'timestamp': '2019-10-06T15:22:42.944Z', 'cached': True}
查找并解析我写的这个特定的字典:
def get_price(self, symbol: str = 'XBTUSD'):
'''contract current price'''
bitmex = self.init_request()
response = bitmex.instrument_GET()
for contract in response:
if not contract['symbol']:
pass
elif contract['symbol'] == symbol:
price = contract['lastPrice']
logger.info('{} price: {}'.format(contract, price))
return price
else:
raise ValueError('could not find {} contract'.format(symbol))
并调用它来查找 XBTUSD 价格,这是lastPrice
键的值
price = BitMEXFunctions().get_price('XBTUSD')
但这每次都会返回 ValueError ,即使我在上面的示例中粘贴了 XBTUSD dict ? 我是否正确解析列表?
追溯:
Traceback (most recent call last):
File "/Users/dev/bot/bordemwrapper/test.py", line 3, in <module>
price = BitMEXFunctions().get_price('XBTUSD')
File "/Users/dev/bot/bordemwrapper/bordemwrapper.py", line 801, in get_price
raise ValueError('could not find {} contract'.format(symbol))
ValueError: could not find XBTUSD contract
您应该将raise ValueError
放在for
循环之外,以便仅在for
循环无法匹配您要查找的符号后引发错误:
for contract in response:
if contract.get('symbol') == symbol:
price = contract['lastPrice']
logger.info('{} price: {}'.format(contract, price))
return price
raise ValueError('could not find {} contract'.format(symbol))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.