Allie H Allie H - 1 month ago 7
Python Question

python iteratively deleting dictionaries with key value

If I wanted to iterate over a group of dictionaries, deleting all dictionaries where the value of a certain key was zero, how could I do that?
I originally tried the code below, but that obviously doesn't work in many cases, as the length of the group decreases as objects are deleted.

data = [{'symbol': 'AA', 'sum': 0}, {'symbol': 'BB', 'sum': 0}, {'symbol': 'CC', 'sum': 10}]

for i in range (0, len(data)):
if data[i]["sum"] == 0:
del data[i]

Answer

It's not really a good idea to delete elements from a list while you go over the list.

A much pythonic solution will be:

data = [{'symbol': 'AA', 'sum': 0}, {'symbol': 'BB', 'sum': 0}, {'symbol': 'CC', 'sum': 10}]
data = [x for x in data if x['sum'] != 0]

This way we create a list based on all of the items we already have in data if the item['sum'] != 0