【问题标题】:In Python, Is there a way to fetch value from the nested dictionary binded in list type在 Python 中,有没有办法从绑定在列表类型中的嵌套字典中获取值
【发布时间】:2017-04-13 06:52:36
【问题描述】:

我有这样的输出

  >>> print output
  [{u'MachineId': u'0', u'Stdout': u'{"version":"2.1-beta2.1-xenial-amd64","url":"file:///tmp/juju-tools137740170/tools/released/juju-2.1-beta2-xenial-amd64.tgz","sha256":"70a1ec4e9d194f71506b9b2944357335d3dbe5386e7797de3ed71c12092ba774","size":24537713}'}]
 >>> type (output)
 <type 'list'>

 >>> print output[0]
 {u'MachineId': u'0', u'Stdout': u'{"version":"2.1-beta2.1-xenial-amd64","url":"file:///tmp/juju-tools137740170/tools/released/juju-2.1-beta2-xenial-amd64.tgz","sha256":"70a1ec4e9d194f71506b9b2944357335d3dbe5386e7797de3ed71c12092ba774","size":24537713}'}
 >>>
 >>> type (output[0])
 <type 'dict'>

在此我想从 output[0] 和 Stdout 字典中获取 sha256 值; 让我知道是否有一种直接的方法可以在 Python 中获取这个值而不是迭代。

如果我尝试直接访问它们,我得到“TypeError:字符串索引必须是整数”

     >>> print output[0]['Stdout']['sha256']
     Traceback (most recent call last):
     File "<console>", line 1, in <module>
     TypeError: string indices must be integers

【问题讨论】:

  • 您的 Stdout 是另一个 JSON 字符串,您必须先对其进行解码,然后才能拥有带有 'sha245' 键的字典。
  • @MartijnPieters 告诉我从输出中获取 sha256 值的方法。
  • 这里有什么问题?如果结构和键名保持不变,您应该可以使用output[0]['Stdout']['sha256']轻松获取
  • @MayurBuragohain;我试过了,我得到以下错误 >>> print output[0]['Stdout']['sha256'] Traceback (最近一次调用最后): File "", line 1, in TypeError : 字符串索引必须是整数
  • 为什么这个问题的负 cmets 为 -4?是我问错了吗:(

标签: python dictionary


【解决方案1】:

您可以通过将Stdout 字符串转换为 json 来获取 sha256 值,例如:

import json
print json.loads(output[0]['Stdout'])['sha256']

【讨论】:

  • 为什么需要 json.loads?从问题中可以看出 output 和 output[0] 分别是 list 和 dict。
  • @MayurBuragohain,请参阅 Marty Pieters 的评论,基于 Viswesn Stdout 报告的错误是 JSON 字符串而不是字典,
猜你喜欢
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 2022-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多