Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple dictionaries in a list

I have been trying to delete multiple dictionaries in a list but I can only delete one at a time.

Below is the main code I am working on. Records is the list of dictionaries. I want to delete dictionaries that have 0 in them.

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

I want to delete dictionaries with Prices of 0

def deleteUnsold(self):
    for d in records:
        for key, value in d.items():
            if d['Price'] == 0:
                records.remove(d)
like image 314
MrKay Avatar asked Jan 13 '16 09:01

MrKay


People also ask

How do you delete multiple items from a list at once in Python?

Remove Multiple elements from list by index range using del. Suppose we want to remove multiple elements from a list by index range, then we can use del keyword i.e. It will delete the elements in list from index1 to index2 – 1.


2 Answers

Use a list comprehension with an 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 out if/else in Python's list comprehension? to learn more about using a conditional within a list comprehension.


Note that [as mentioned below] you can also leave out checking for the value 0. However this also works if Price is None, hence you may use the first alternative if you are not sure of the data type of the value of Price

>>> [i for i in Records if i['Price']]
[{'Price': 10, 'Name': 'Michael'}]
like image 160
Bhargav Rao Avatar answered Nov 14 '22 22:11

Bhargav Rao


You can use filter:

print filter(lambda x:x['Price']!=0,Records)
like image 30
Ahsanul Haque Avatar answered Nov 14 '22 21:11

Ahsanul Haque