python - remove dictionary from list if exists

2020-07-12 21:05发布

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

标签: python
4条回答
太酷不给撩
2楼-- · 2020-07-12 21:17

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

查看更多
▲ chillily
3楼-- · 2020-07-12 21:26
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.

查看更多
走好不送
4楼-- · 2020-07-12 21:30

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
查看更多
Explosion°爆炸
5楼-- · 2020-07-12 21:31

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.

查看更多
登录 后发表回答