Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clear a dictionary after return Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I will appreciate it any help,

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading