Python generally frowns upon changing the size of a dict while iterating over it. That’s because the results are not entirely reliable. If that was allowed, then entries might be skipped, or reached twice.
The usual recommendation is not to remove entries from the existing dict, but to construct an entirely new dict, appropriately filtered.
so something like
trimmed_dict = { k: k for v in votes_for_candidates if v is not 0 }
print (trimmed_dict.items())
That’s the general idea. Off the top of my head, the syntax would be something like:
trimmed_dict = {
key: value
for key, value in votes_for_candidates.items()
if value != 0
}
print (trimmed_dict)
Notes:
-
is and is not are tests for object identity, not equality. They work for singleton values like None, which is guaranteed by the language to have only one instance in the entire program. In general, numbers don’t have that same guarantee. Use == and != for numbers.
- If
value can be None, and you want to skip that, too, then the test can be simplified to if value. if treats both None and zero as being False.
- Personal preference: For readability, I like to separate the clauses with newlines, or at least two spaces.
1 Like
Since we are talking about personal preferences, even better, get familiar with the concept of truthy and falsy, and use if value.
2 Likes