Alirezaro93
Alirezaro93

Reputation: 67

Removing all the keys in a dictionary for which their value is 0

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

Answers (3)

ted
ted

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

Red
Red

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

Sciborg
Sciborg

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

Related Questions