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:
JavaScript
x
14
14
1
my_final_return={}
2
3
@api_router.get("/example-stackoverflow", tags=['Simulations'])
4
def example(*,current_age:int):
5
6
ages_list = [current_age,40,45,50]
7
8
for i in ages_list:
9
my_final_return[i]={
10
"current_age":i*2
11
}
12
13
return my_final_return
14
The result in first execution is correct:
However if I add a different age the new one is added also (my problem):
Advertisement
Answer
your dictionary is instantiated outside of the function.
JavaScript
1
13
13
1
2
@api_router.get("/example-stackoverflow", tags=['Simulations'])
3
def example(*,current_age:int):
4
my_final_return={}
5
ages_list = [current_age,40,45,50]
6
7
for i in ages_list:
8
my_final_return[i]={
9
"current_age":i*2
10
}
11
12
return my_final_return
13
this will clear it out when you call the function again