I am trying to remove a dictionary from a list if it already exists but it doesn't seem to be working. Can anyone see what I am doing wrong or advise me what I should be doing
new_dict = {'value': 'some value', 'key': 'someKey'}
if new_dict in my_list:
my_list.remove(new_dict)
new_list is a list of dictionaries where new_dict is definitely in
If
new_dict
is "definitely" inmy_list
, thenmy_list.remove(new_dict)
should do the trick (i.e., no need for theif new_dict in my_list
, that just slows it down).It worked for both of the dictionaries for me.
Your problem may come from the fact that removing from a list while iterating over the same list is not safe. What you want to do is something like:
This way, you iterate over a copy of the list and remove from the original.
This may not be the cause of your problem though. It would be interesting to see:
my_list
my_list
after the loop, i.e. how do you realise your dictionary was not removedIn most cases it is clever to build a new list:
This is typical for a functional programming style, as it avoids side effects. Imagine if you use your solution in a function or method. In most cases you need a modified list only for internal purposes, then modifying an input parameter is dangerous.