【问题标题】:assign values of nested dict to list in python将嵌套字典的值分配给python中的列表
【发布时间】:2017-12-30 20:08:38
【问题描述】:

我有一个 JSON 对象列表的文件。它看起来像这样:

[
  {
    "id": 748,
    "location": {
      "slug": "istanbul",
      "parent": {
        "id": 442,
        "slug": "turkey"
      }
    },
    "rank": 110
  },
  {
    "id": 769,
    "location": {
      "slug": "dubai",
      "parent": {
        "id": 473,
        "slug": "uae"
      }
    },
    "rank": 24
  }
]

我想创建一个酒店父名称列表,所以我编写了这段代码来执行此操作,我读取 JSON 文件并将其分配给一个变量,那部分是正确的。但是看看这段代码:

with open('hotels.json', 'r', encoding="utf8") as hotels_data:
    hotels = json.load(hotels_data)

parents_list = []
for item in hotels:
    if item["location"]["parent"]["slug"] not in parents_list:
        parents_list.append(item["location"]["parent"])

当我运行这段代码时,我给出了这个错误:

if item["location"]["parent"]["slug"] not in parents_list:
TypeError: 'NoneType' object is not subscriptable

这段代码不起作用,所以我尝试打印 JSON 对象,所以我在循环中写了这个:

print(item["location"]["parent"]["slug"])

这段代码打印了我想要的值,但也给了我完全相同的错误。 感谢您的任何帮助。

【问题讨论】:

  • 此代码是否因给定示例数据而失败?
  • 你用的是python3还是python2?
  • 我正在使用 python 3.6
  • 您发布的数据中似乎没有出现问题。您可以将 json 文件上传到某处并将链接添加到您的问题吗?

标签: json python-3.x dictionary nested


【解决方案1】:

我尝试运行代码,它似乎与您的数据集配合良好。

但是,我没有打开文件来读取数据,而是将您的数据集 hotels = [...] 分配给了酒店。

我得到的结果是这样的:

[{'id': 442, 'slug': 'turkey'}, {'id': 473, 'slug': 'uae'}]

如果你打印hotels,你的结果是什么,和你这里显示的一样吗?


如果您的数据集中实际上有更多数据,那么我可以假设某些字典不包含item["location"]["parent"]["slug"]。如果是这种情况,您应该先检查每个item 中是否存在该元素,然后再从parents_list 读取,从而跳过这些。

例如:

try:
    item["location"]["parent"]["slug"]
except (KeyError, TypeError) as e:
    pass
else:
    if item["location"]["parent"]["slug"] not in parents_list:
        parents_list.append(item["location"]["parent"])

【讨论】:

  • 我在测试 OPs 代码时得到了相同的数组
  • 现在已经修好了,但我必须像这样检查所有级别的 dict:if item["location"]: if item["location"]["parent"]: if item["location"]["parent"]["slug"]: if item["location"]["parent"]["slug"] not in parents_list: parents_list.append(item["location"]["parent"]["slug"]) 有没有更好的方法来检查?
  • @Amirition 抱歉,请按照我在回答中的建议使用 tryelse
  • 它在item["location"]["parent"]["slug"] 行与您建议的代码给出了相同的错误。
  • @Amirition 我的示例代码运行良好。空字典作为 KeyError 传递。确保您有正确的缩进,尤其是if 行。您的完整错误信息是什么?
【解决方案2】:

我无法复制与您相同的错误。我能想到的唯一一件事是 JSON 中每个对象的最后一项后面不应该有逗号。看看这是否能解决你的错误

【讨论】:

  • 是的,这是我在写问题时犯的一个错误,我更正了。
  • 这实际上是文件中的问题。现在好了。谢谢。
猜你喜欢
  • 2021-12-27
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多