2

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.

Josh Wren
  • 338
  • 2
  • 12
  • You can always new another copy of your list and filter out the original value. I don't really think delete on fly is a good practise. – Kuang Wenyi Aug 08 '21 at 21:57
  • https://stackoverflow.com/questions/3485475/can-i-create-a-view-on-a-python-list Or you could use something like this, make a read-only list and do coping based on it. – Kuang Wenyi Aug 08 '21 at 22:03

1 Answers1

2

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 ]
Mohammad
  • 3,276
  • 2
  • 19
  • 35