访问python中的嵌套字典

时间:2017-08-29 13:47:26

标签: python dictionary

我正在尝试从下面的字典中访问creator的值以及描述和电子邮件等其他值。

我尝试将其转换为json,然后访问密钥。但它没有用。是迭代整个字典并获取所有键值的唯一方法。

任何建议都会很棒!!

  {
    "description": xxx,
    "email": xxx@scotiabank.com,
    "creator": {
       "data": [
          {
              "name": "john" 
              "id": "123"
          },
          {
              "name": "victor"
              "id" : "345"
          }
        ]
  }

2 个答案:

答案 0 :(得分:0)

假设你有一本任何深度的字典。

dict = {"description": xxx, ...

您可以通过指定密钥来获取字典中的项目:

desc = dict["description"] # returns "xxx"

你可以递归地执行此操作:

name = dict["creator"]["data"] # returns list of people [{"name": "john", "id": "123"}, {"name": "victor", "id": "345"}]
name = dict["creator"]["data"][0] # returns the first item in the list {"name": "john", "id": "123"}
name = dict["creator"]["data"][0]["name"] # returns "john"

答案 1 :(得分:0)

dict["description"]将返回'xxx'

dict["creator"]['data']将返回[{"name": "john","id": "123"},{"name": "victor","id" : "345"}]

dict["creator"]['data'][1]["name"]将返回"john"

dict是你的词典

相关问题