'Cannot iterate through a dict in python

I have a packages.json file and this is an example of what it contains:

{
    "1": {
        "name": "package 1",
        "price": 1450,
        "discount_info": {
            "is_discount": false,
            "discount_percentage": 0,
            "remaining_secs": 0
        }
    },
    "2": {
        "name": "package 2",
        "price": 365,
        "discount_info": {
            "is_discount": false,
            "discount_percentage": 0,
            "remaining_secs": 0
        }
    }
}

and I load it through:

packages = json.loads(open("packages.json", "r", encoding='utf-8').read())

Later I want to iterate through these packages and check the discount_info of each one, and when the is_discount is true I want to run a function in a thread to -1 from "remaining_secs" each second then re-update the dict using:

def update_packages():
    with open('packages.json', mode='w', encoding='utf-8') as f:
        json.dump(packages, f, ensure_ascii=False, indent=4)

Then when the iteration ends, I want to set the default discount_info which is:

"discount_info": {
  "is_discount": false,
  "remaining_secs": 0,
  "discount_percentage": 0
}

Here is my iteration code:

for package in packages:

    if packages[package]['discount_info']['is_discount'] == True:

        def thread_fun():
            while packages[package]['discount_info']['remaining_secs'] > 0 and packages[package]['discount_info']['is_discount']:
                packages[package]['discount_info']['remaining_secs'] -= 1
                update_packages()
                sleep(1)

            packages[package]['discount_info'] = {
                'is_discount': False,
                'remaining_secs': 0,
                'discount_percent': 0,
            }
            update_packages()

        threading.Thread(target=thread_fun).start()

But I noticed that the iteration runs only once then stop and I do not know why, I tried to debug and print some stuff and I got that sometimes the remaining_secs turn to -1 from the first iteration.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source