在python中访问嵌套字典

2024-10-01 13:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从下面的字典中访问creator的值以及其他值,如description和email。在

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

有什么建议都很好!!在

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

Tags: 方法namecomidjsondata字典email
2条回答

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

dict["creator"]['data']将返回{}

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

你的字典在哪里

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

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

可以通过指定键从字典中获取项:

^{pr2}$

可以递归执行此操作:

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"

相关问题 更多 >