【问题标题】:Python - Extract specific items from nested dictionaryPython - 从嵌套字典中提取特定项目
【发布时间】:2021-02-22 00:19:22
【问题描述】:

在做一个小项目,我可能会不知所措。使用 CoinMarketCap API,我试图了解如何解析他们的结果以提取返回值的特定部分。

举个例子:

  result = {'status': {'timestamp': '2021-02-22T00:04:51.978Z', 'error_code': 0, 'error_message': None, 'elapsed': 46, 'credit_count': 1, 'notice': None}, 'data': {'1INCH': {'id': 8104, 'name': '1inch', 'symbol': '1INCH', 'slug': '1inch', 'cmc_rank': 83, 'last_updated': '2021-02-22T00:03:09.000Z', 'quote': {'BTC': {'price': 8.793673178965842e-05, 'volume_24h': 4010.9008604493424, 'percent_change_1h': 1.77689058, 'percent_change_24h': -3.76351861, 'percent_change_7d': -19.9798068, 'percent_change_30d': 66.4333541, 'market_cap': 12615.667000751586, 'last_updated': '2021-02-22T00:03:02.000Z'}}}}}

我无法弄清楚如何从该变量中提取“symbol”、“cmc_rank”和“market_cap”值。这样做的正确方法是什么?

谢谢

【问题讨论】:

    标签: python dictionary cryptocurrency


    【解决方案1】:

    试试这个解决方案,它应该会给你想要的东西:

    symbol     = result['data']['1INCH']['symbol']
    cmc_rank   = result['data']['1INCH']['cmc_rank']
    market_cap = result['data']['1INCH']['quote']['BTC']['market_cap']
    

    【讨论】:

      【解决方案2】:

      你试过了吗?

      print(result["data"]["1INCH"]["symbol"])
      print(result["data"]["1INCH"]["cmc_rank"])
      print(result["data"]["1INCH"]["quote"]["BTC"]["market_cap"])
      
      

      【讨论】:

        【解决方案3】:

        “{}”表示python dict(字典)——(方括号[] 是一个列表,括号() 是一个元组)。字典也可以嵌套(与列表和元组相同)

        在这种情况下,您有一个嵌套字典。做一些缩进很有帮助...

        result = {
        'status': {
            'timestamp': '2021-02-22T00:04:51.978Z', 
            'error_code': 0, 
            'error_message': None, 'elapsed': 46, 'credit_count': 1, 'notice': None}, 
        'data': {
            '1INCH': {
               'id': 8104, 'name': '1inch', 'symbol': '1INCH', 'slug': '1inch', 'cmc_rank': 83, 'last_updated': '2021-02-22T00:03:09.000Z', 
                'quote': {
                    'BTC': {
                        'price': 8.793673178965842e-05, 'volume_24h': 4010.9008604493424, 'percent_change_1h': 1.77689058, 'percent_change_24h': -3.76351861, 'percent_change_7d': -19.9798068, 'percent_change_30d': 66.4333541, 'market_cap': 12615.667000751586, 'last_updated': '2021-02-22T00:03:02.000Z'}}}}}
        

        dict中冒号(:)左边的部分是key,右边的部分是value。

        所以在你给出的例子中:result['data']['1INCH']['symbol'] 会给你符号的价值,result['data']['1INCH']['quote']['BTC']['market_cap'] 会给你市值的价值。

        但是,这只有在键不变的情况下才有效。在这种情况下,看起来结果以符号 ('1INCH') 作为键返回。与货币('BTC')相同。如果您总是期待“1INCH”和“BTC”,那么您可以对其进行硬编码。另一方面,如果符号和/或货币发生变化,您可能希望 (a) 存储变量并改用这些变量(例如 symbol='1INCH' .... result = x.query(symbol).... 结果['data'][symbol].....) 或 (2) 获取密钥或 (3) 循环。

        要获取任何字典的键列表——在本例中,字典“数据”的键:dkeys = list(result['data'].keys()) ...然后您可以使用len(dkeys) 检查长度和/或访问键带有数字(因为它是一个列表)dkeys[0]。所以,像result['data'][dkeys[0]]...

        或者您可以循环 - 如果您有多个结果,那就太好了:

        #the .items() method will return 2 values - the key and value for each entry
        for k, v in result['data'].items():
          #k would be the symbol in this case and v is the dictionary represented by that key
          market_cap = v['quote']['BTC']['market_cap']
          #note if there are multiple symbols here, it would overwrite market_cap...
        
        

        【讨论】:

          猜你喜欢
          • 2023-02-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-12
          • 2016-05-15
          • 2021-04-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多