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)
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.
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'}]
You can use filter:
print filter(lambda x:x['Price']!=0,Records)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With