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" in my_list
, then my_list.remove(new_dict)
should do the trick (i.e., no need for the if new_dict in my_list
, that just slows it down).
my_list = [1,{'value':'some value', 'key' :'somekey'}, 2, {'z':'z', 'x': 'x'}]
new_dict = {'value':'some value', 'key' :'somekey'}
#new_dict = {'z':'z', 'x': 'x'}
differ = 0
matched = 0
for element in my_list:
if type(element) is types.DictType and matched != 0:
differ = 0
# check if dictionary keys match
if element.viewkeys() == new_dict.viewkeys():
# check if dictionary values match
for key in element.keys():
if element[key] != new_dict[key]:
differ = 1
matched = 1
if differ != 1:
my_list.remove(new_dict)
print my_list
It worked for both of the dictionaries for me.
In most cases it is clever to build a new list:
new_list = [ dd for dd in my_list if not dd is new_dict ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With