在Python中,有没有办法从列表类型中绑定的嵌套字典中获取值

时间:2016-11-29 10:11:30

标签: python dictionary

我有这样的输出

  >>> 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'>

在这里我想从输出字典[0]和Stdout字典中获取sha256值; 让我知道有没有直接的方法来获取Python中的这个值而不是迭代。

我得到了#34; TypeError:字符串索引必须是整数&#34;如果我试图直接访问它们

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

1 个答案:

答案 0 :(得分:1)

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

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