How to clear a dictionary after return?

Question:

I am having issue cleaning dictionaries after return the one.
I am using fastAPI and my API GET an Age value then I create a list of ages with 4 values including my received value.

I am looking to receive always 4 values only the input age and the other ones, in first execution the code works correctly but if I change the age the dictionary increase in one and add the new age and I have 5 values in the array.

Example code:

my_final_return={}

@api_router.get("/example-stackoverflow", tags=['Simulations'])
def example(*,current_age:int):

    ages_list = [current_age,40,45,50]
    
    for i in ages_list:
        my_final_return[i]={
            "current_age":i*2
        }

    return my_final_return

The result in first execution is correct:

enter image description here

However if I add a different age the new one is added also (my problem):

enter image description here

Asked By: Nor

||

Answers:

your dictionary is instantiated outside of the function.



@api_router.get("/example-stackoverflow", tags=['Simulations'])
def example(*,current_age:int):
    my_final_return={}
    ages_list = [current_age,40,45,50]
    
    for i in ages_list:
        my_final_return[i]={
            "current_age":i*2
        }

    return my_final_return

this will clear it out when you call the function again

Answered By: 1extralime
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.