frostming / legit

Git for Humans, Inspired by GitHub for Mac™.
https://frostming.github.io/legit
BSD 3-Clause "New" or "Revised" License
5.7k stars 218 forks source link

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

Closed hamikube closed 4 years ago

hamikube commented 4 years ago

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 commented 4 years ago
 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.