考虑迭代 items()

Consider iterating with items()

我正在浏览一本字典以删除另一本字典中的某些值。但是,pylint 不喜欢我的代码并建议我使用 .items() 方法。我发现了这种方法,但我不明白如何用它获得相同的结果。

我的字典是这样的:

itemsToDelete = {
  1: {
  "page1": "item1",
  "page1": "item2",
  "page1": "item3"
  },
  2: {
  "page3": "item1",
  "page3": "item2",
  "page3": "item3"
  },
  3: {
  "page5": "item1",
  "page5": "item2",
  "page5": "item3"
  }
}

contents = {
  1: {
  "page1": "item1",
  "page1": "item2",
  "page1": "item3",
  "page1": "item4",
  "page1": "item5"
  },
  2: {
  "page3": "item1",
  "page3": "item2",
  "page3": "item3"
  },
  3: {
  "page5": "item1",
  "page5": "item2",
  "page5": "item3"
  }
}

其实我是这样浏览的:

for package in itemsToDelete:
    for page in itemsToDelete[package]:
        for item in itemsToDelete[package][page]:
            if item in contents[package][page]:
                del contents[package][page][item]

我怎么能用 items() 做同样的事情? 感谢您的帮助

pylint 警告您可以通过使用字典的 items 方法来避免冗余的 itemsToDelete[package] 表达式。

所以试试这个:

for package, package_items in itemsToDelete.items():
    for page, package_item in package_items.items():
        for item in package_item:
            if item in contents[package][page]:
                del contents[package][page][item]