【问题标题】:Access nested dictionaries in python [duplicate]在python中访问嵌套字典[重复]
【发布时间】:2018-02-07 00:18:48
【问题描述】:

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

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

任何建议都会很棒!!

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

【问题讨论】:

  • 您应该展示您的尝试并解释“无效”的含义。
  • 不会是dictionary["creator"]["data"]吗?

标签: python dictionary


【解决方案1】:

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

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"

【讨论】:

  • 这适用于非嵌套字典,但不适用于嵌套字典!
  • @user3447653:我已经编辑了我的答案。这是否使它更清楚?如果没有,你到底想达到什么目的?
  • 您可能想更详细地解释这里发生了什么。
  • 感谢您提供此代码 sn-p,它可能会提供一些即时帮助。一个正确的解释would greatly improve 其教育价值通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有类似但不相同的问题的读者更有用。请edit您的答案添加解释,并说明适用的限制和假设。
【解决方案2】:

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

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

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

dict 是你的字典

【讨论】:

    猜你喜欢
    • 2020-10-03
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多