Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to fix "RuntimeError: dictionary changed size during iteration" in Python? #260

Closed
hamikube opened this issue Oct 17, 2019 · 1 comment

Comments

@hamikube
Copy link

I want to fix the mentioned issue in the following codes:

while (len(weights) > 0) and (capacity > 0):
    total_shares = sum(weights.values())
    unit_share = capacity/total_shares
    user_list = weights.keys()
    for user in user_list:
        fair_share = unit_share * weights[user]
        current_share[user] += fair_share
        if current_share[user] >= desired[user]:
            spare_capacity = (current_share[user] - desired[user])
            final_share[user] = desired[user]
            del current_share[user]
            del weights[user]
            capacity = capacity + spare_capacity - fair_share
        else:
            capacity = capacity - fair_share

When I run the program, the following issue appears:

for user in user_list:
RuntimeError: dictionary changed size during iteration

How can I fix that runtime error issue?

@frostming
Copy link
Owner

frostming commented Oct 18, 2019

 user_list = weights.keys()
 for user in user_list:
    ...
    del weights[user]

weight.keys() is a keyview of weights, which relies on the underlying storage of the dictionary, so you were iterating over weigts while deleting something from it.

To fix it, you should use a copy of the keys list instead:

user_list = list(weigts.keys())

BTW, it is not related to this project. Close it now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants