Home > Mobile >  Consider iterating with items()
Consider iterating with items()

Time:10-23

I'm browsing a dictionary to delete some values in another dictionary. However, pylint doesn't like my code and suggest me to use .items() method. I discover this method and I don't understand how to get the same result with this.

My dictionaries look like that :

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"
  }
}

Actually I browse them like this :

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]

How could I do the same thing with items() ? Thank you for your help

CodePudding user response:

pylint warns you that you can avoid redundant itemsToDelete[package] expressions by using the items method of dictionaries.

So try this instead:

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