Search code examples
pythonpython-3.xlist-comprehensiondictionary-comprehension

Removing element from a list in a for loop


I have a list that has lists with dictionaries in them. I'm trying to check one of the values for a key inside the dictionary and if it's try then I remove that list from the list. I'm getting a bit confused with the layers of lists and dictionaries going on here and I thought I had a good solution but it seems to mess with the index of the for loop when I do it the way that I thought would work and then only the first match gets removed.

Here's an example of what I have going on.

master_list = [
  {"irrelevant_key": "irrevelant_value", 
   "releveant_key": 
                  [{"first_value": "first_key"}, {"problem_key": 0}],
                  [{"second_value": "second_key"}, {"problem_key": 1}]
  }]

for index, key in enumerate(master_list):
  for item in master_list[index]["relevant_key"]:
    if item[1]["problem_key"] == 0:
      master_list[index]["relevant_key"].remove(item)

So I'm sure there's a more elegant better way to do this with some sort of comprehension but what I'm noticing is that when I delete the item the rest of the items go back one so the iteration doesn't work as I would expect.


Solution

  • It's not a good idea to remove elements from a list while looping through it. You can always make a copy and update it:

    import copy
    my_list= copy.deepcopy(master_list)
    

    However, a better approach would be to use list comprehensions:

    master_list = [{"irrelevant_key": "irrevelant_value", 
                    "relevant_key": 
                      [[{"first_value": "first_key"}, {"problem_key": 0}],
                      [{"second_value": "second_key"}, {"problem_key": 1}]],
                    }]
    for lst in master_list:
      lst['relevant_key'] = [x for x in lst['relevant_key'] if x[1]['problem_key'] != 0 ]