Why does my condition only eliminate the first key/value pair in my dictionary?

30 views Asked by At

I'm currently working on a problem relating to dictionaries where you write a function that deletes all key/value pairs in which a value is larger than a given number. Here is the code:

def remove_numbers_larger_than(number, dict1):
    for i, value in dict1.items():
        if value > number :
            del dict1[i]
            return dict1
        else:
            return dict1


dict1 = {'animals': 6 , 'truck': 3, 'country': 2}
number = 2

print(remove_numbers_larger_than(number, dict1))

Normally I would expect to see output: {'country': 2} given that it is the only value smaller than the given number but instead I get output: {'truck': 3, 'country': 2}. It seems to be taking the initial condition and removing the first value but then the loop stops.

1

There are 1 answers

0
Leo Adberg On

Only the first item is getting deleted because you immediately return from the function in the first iteration of the for loop. To loop through every value, you shouldn't return until after the for loop is over.

However, there's also another issue with the code. You are iterating through a list (dict1.items()) which will change when you remove items from the dictionary. An easy fix is to make a copy of the items list that you iterate over, allowing the original list to change without problems:

for i, value in list(dict1.items()):