Reputation: 63
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)
Upvotes: 6
Views: 1246
Reputation: 5866
Okay, generally speaking you shouldn't remove items from a list you're iterating for, because that will probable make you miss some items of the list.
Now, about some other answer spoken here, yes, they work, but strictly speaking they're not removing/deleting items from the list: they're creating a new list and replacing the old variable with a new list.
What could 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)
Upvotes: 0
Reputation: 52181
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'}]
Upvotes: 12
Reputation: 11164
You can use filter:
print filter(lambda x:x['Price']!=0,Records)
Upvotes: 2