Why is my dictionary of type Dict inside the function, but type NoneType when it's returned from it?

I have a function designed to increment the lowest values in a inputted dictionary object until all values are the same:

def add_to_smallest(kwargs): if len(list(set(list(kwargs.values())))) == 1: print("all values in dict are the same") print(kwargs) return kwargs else: index = min(kwargs.values()) for key, value in kwargs.items(): if value == index: kwargs[key] += 1 add_to_smallest(kwargs) add_to_smallest({"pos1": 60, "pos2": 54, "pos3": 300, "pos4": 5})

it’s a recursive function, and if I print type of the kwargs dictionary inside the base case if clause this is the input I get:

>> print(type(kwargs))
`<class 'dict'>`

my function is returning the kwargs dictionary when it’s done which means that if I assign the function call to a variable, that variable should hold a dict object right?
but that doesn’t seem to be the case if I try doing this:

output_dict = add_to_smallest({"pos1": 60, "pos2": 54, "pos3": 300, "pos4": 5})

this is the output I get:
<class 'NoneType'>
Why is this happening?

I am going to try to explain this one, even though I understand it, I always find it difficult to put the explanation into words, so please bear with me.

the problem is here:


your function call in the else clause.

when we reach the base (the if clause), we return the dictionary:

return kwargs

now all the recursive calls will be resolved, but you forgot the return keyword. If we add the return keyword:

return add_to_smallest(kwargs)

the resolved function call which actual return the value its get handed back (either from the base case or other resolving function calls)


Thanks so much!
That basically means that the return statement in my base case, will only be returned, if the function call that caused it is also returned, other wise, nothing will be returned.

1 Like