在一长串字典中查找特定的字典

问题描述 投票:1回答:1

[嗨,我正在使用一个响应很长的字典的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')

但是,即使我在上面的示例中粘贴了XBTUSD字典,也每次都会返回ValueError?我是否正确解析列表?

回溯:

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

[嗨,我正在使用一个响应很长的字典的api。我试图根据输入的参数查找并解析其中的特定一个。以下是这些示例之一的示例...

python
1个回答
1
投票

您应将raise ValueError放在for循环之外,以便仅在for循环与您要查找的符号不匹配后才引发错误:

© www.soinside.com 2019 - 2024. All rights reserved.