开发者

python - remove dictionary from list if exists

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开发者_JAVA技巧_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.


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:

copied_list = my_list[:]
if new_dict in copied_list:
    my_list.remove(new_dict)

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:

  • how you build my_list
  • what you do with my_list after the loop, i.e. how do you realise your dictionary was not removed
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜