Delete multiple dictionaries in a list

I am trying to delete several dictionaries in a list, but I can only delete them at a time.

Below is the main code I'm working on. Entries is a list of dictionaries. I want to delete dictionaries that have 0.

Records = [{'Name':'Kelvin','Price': 0},{'Name': 'Michael','Price':10}] 

I want to delete dictionaries with price 0

 def deleteUnsold(self): for d in records: for key, value in d.items(): if d['Price'] == 0: records.remove(d) 
+5
source share
3 answers

Use list comprehension with if condition

 >>> Records = [{'Name':'Kelvin','Price': 0},{'Name': 'Michael','Price':10}] >>> [i for i in Records if i['Price'] != 0] [{'Price': 10, 'Name': 'Michael'}] 

Check if / else in Python list comprehension? to learn more about using conditional expressions in an understanding list.


Please note that [as indicated below ] you can also ignore the value 0 . However, this also works if Price is None , so you can use the first option if you are not sure about the data type of the Price value.

 >>> [i for i in Records if i['Price']] [{'Price': 10, 'Name': 'Michael'}] 
+11
source

You can use filter :

 print filter(lambda x:x['Price']!=0,Records) 
+2
source

Well, generally speaking, you should not remove items from the list that you iterate, because this will probably make you skip some items in the list.

Now about some other answer that is said here, yes, they work, but, strictly speaking, they do not delete / do not remove elements from the list: they create a new list and replace the old variable with a new list.

What can be done:

 for d in list(records): if d['Price'] == 0: records.remove(d) for d in reversed(records): if d['Price'] == 0: records.remove(d) for idx in range(len(records)-1,-1,-1): if records[idx]['Price'] == 0: records.pop(idx) 

I like this one though:

 for d in records[::-1]: if d['Price'] == 0: records.remove(d) 
0
source

Source: https://habr.com/ru/post/1240509/


All Articles