Code with comments:
result = {}
def number_of_products():
return 1 # 2, 3...n
def total_inventory():
return 100 # 200, 300... n
def set_values():
result["numberOfProducts"] = number_of_products()
result["totalInventory"] = total_inventory()
def run_orders():
results = []
for i in range(4):
set_values()
# result = {'numberOfProducts': 1, 'totalInventory': 1000} for the first iteration
# result = {'numberOfProducts': 2, 'totalInventory': 2000} for the first iteration
...
# Add result to the array for future use.
results.append(result)
# Clean up the dictionary for reuse.
result.clear()
print(results)
# Expectation
# [{'numberOfProducts': 1, 'totalInventory': 1000}, {'numberOfProducts': 2, 'totalInventory': 2000}, ...]
# Actual
# [{},{},...]
run_orders()
As you can see, I am getting empty values in the array when I use the .clear()
method.
I also tried using result = {}
but that gave the following result:
[{'numberOfProducts': 1, 'totalInventory': 1000}, {'numberOfProducts': 1, 'totalInventory': 1000}, {'numberOfProducts': 1, 'totalInventory': 1000}, ...]
How can I persist the values I get from different result(s)?