Python - 从嵌套字典中提取特定项目

Python - Extract specific items from nested dictionary

在做一个小项目时,我可能会不知所措。使用 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' 值。这样做的正确方法是什么?

谢谢

试试这个解决方案,它应该能满足您的需求:

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

你试过了吗?

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

“{}”表示 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'}}}}}

字典中冒号(:)左边的部分是,右边的部分是值。

因此在您给出的示例中:result['data']['1INCH']['symbol'] 会给出符号的值,result['data']['1INCH']['quote']['BTC']['market_cap'] 会给出市值的值。

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

要获取任何字典的键列表——在这个例子中,字典的键 'data' : dkeys = list(result['data'].keys()) ...然后你可以用 [=15 检查长度=] and/or 使用数字访问密钥(因为它是一个列表)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...