Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - remove dictionary from list if exists

Tags:

python

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

like image 458
John Avatar asked Sep 20 '11 11:09

John


3 Answers

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).

like image 96
Fred Foo Avatar answered Oct 27 '22 07:10

Fred Foo


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.

like image 32
avasal Avatar answered Oct 27 '22 08:10

avasal


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.

like image 37
rocksportrocker Avatar answered Oct 27 '22 08:10

rocksportrocker