I have a list like this:
bloqueOrdenApi = [{'Articulos': 0}, {'Libros': 0}, {'Proyectos': 5}, {'GradoAcademico': 7}, {'Capacitacion': 8}]
I am trying to remove the dictionaries whose value is 0, in this case Articles and Books, I am doing this:
for b in bloqueOrdenApi:
for k, v in b.items():
if v == 0:
del bloqueOrdenApi[v]
print(bloqueOrdenApi)
But I get as output this:
bloqueOrdenApi = [{'Libros': 0}, {'Proyectos': 5}, {'GradoAcademico': 7}, {'Capacitacion': 8}]
Only the Articles element is deleted and Books are not. How can I remove all dictionaries that have a value of 0? I hope you can help me. Thanks in advance.
I don't recommend using
del
to remove items from a list, instead use the methodpop()
, asdel
it is used for other things.Your mistake is that you always eliminate the first element, by doing so
del bloqueOrdenApi[v]
you are eliminating from the listbloqueOrdenApi
the elementv
that willif
always be valid for you0
. Another thing is that when the element is eliminated, the next one will be omitted, this is because, for example, if the element0
is eliminated, the next one is the element1
and the one that now occupies the position1
is the one that was previously the second.I think one way to avoid confusion is by using a list comprehension.
Here we only get the values and since the result is a
dict_values()
we will convert it to a list withlist()
and this time we compare with[0]
Exactly, Christian's answer is absolutely right, I created a function that, in order not to eliminate the first index, I made a repetition according to the length of the list:
But undoubtedly the Christian code is what reflects the simplicity of python. Very good Christian. Greetings to all