Reputation: 67
I have a dictionary in Python for which I want to remove all the keys that have a value of exactly 0. It's a large dictionary so I cannot copy it here, but lets say this is my dictionary:
grades = {mark: 0, Andrew: 0.01, Alex: 0, Sam: 0, Eric: 0.02}
The result should look like this:
grades = {Andrew: 0.01, Eric: 0.02}
Thanks for your help
Upvotes: 1
Views: 934
Reputation: 14684
Use a dict comprehension:
grades = {mark: 0, Andrew: 0.01, Alex: 0, Sam: 0, Eric: 0.02}
non_zeros = {k: v for k, v in grades.items() if v != 0}
or a filter
non_zeros = dict(filter(lambda kv: kv[1] != 0, grades.items()))
or del
for k, v in grades.copy().items():
if v == 0:
del grades[k]
Upvotes: 6
Reputation: 27547
You can use a dict
comprehension:
grades = {mark: 0, Andrew: 0.01, Alex: 0, Sam: 0, Eric: 0.02}
grades = {k:grades[k] for k in grades if grades[k]}
print(grades)
Output:
grades = {Andrew: 0.01, Eric: 0.02}
Upvotes: 2
Reputation: 526
As @ted said, you can use dict comprehension, which is probably the best and most compact solution. Here is an alternative way using basic for-each iteration:
keys = grades.keys() # Get a list of all the keys
for key in keys:
if grades[key] == 0: # If the value is 0...
my_dict.pop(key, None) # Remove the key from the dictionary
Upvotes: 1