【问题标题】:How to retrieve list item at index based on name from Json object in Python如何根据 Python 中 Json 对象的名称检索索引处的列表项
【发布时间】:2019-02-01 21:31:19
【问题描述】:

例如给定以下 JSON:

{
  "success": true,
  "message": "''",
  "result": [
    {
      "buy": [
        {
          "quantity": 12.37,
          "rate": 32.55412402
        }
      ],
      "sell": [
        {
          "quantity": 12.37,
          "rate": 32.55412402
        }
      ]
    }
  ]
}

我将如何检索“买入”和“卖出”以存储到变量中? 我可以通过以下方式获得结果:

d = json.loads(string)

print(d['result'])

但是我现在看不到如何检索购买对象。例如。我试过了:

#print(d['result']['buy'])
#print(d['result'].buy)
#print(d['result'].indexOf('buy'))

一切都无济于事。

【问题讨论】:

    标签: json string list dictionary


    【解决方案1】:

    试试:

    print(d['result'][0]['buy'])

    应该给你购买对象:

    [{u'rate': 32.55412402, u'quantity': 12.37}]
    

    如果您检查typed['result']

    print(type(d['result']))  # <type 'list'>
    

    这是一个长度为1list,因此[0] 末尾的d['result'][0] 将返回列表中的第一个也是唯一一个项目,这是您期望可以通过键@ 获取的字典987654330@ 就像您在第一次尝试时所做的那样:

    #print(d['result']['buy'])
    

    只需要通过[0]索引列表

    #print(d['result'][0]['buy'])
    

    【讨论】:

    • 谢谢!我想知道是否有更明确的引用方式?例如。想象一下,除了“买入”和“卖出”,我们还有 1000 个类似方式的条目,我如何按名称而不是索引?
    • 您的意思是d['result'] 列表中还有1000 个条目吗?那将是for obj in d['result']: print(d['result']['buy'])。如果你真的是说你在同一个列表中还有 1000 多个字典,比如 'Buy''Sell',那么像 for key in d['result'][0].keys(): print(d['result'][0][key]) 这样的字典就可以了。你是这个意思吗?如果不是,可以将结构示例放入问题中,我可以将其包含在答案中,以便阅读
    • 抱歉,对于 d['result'][0].keys() 中的 key 不够清晰: print(d['result'][0][key]) 是我完成后的事情。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-03-05
    • 2023-03-16
    • 2014-11-24
    • 2021-06-07
    • 2013-10-05
    • 2017-08-21
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多