Skip to content Skip to sidebar Skip to footer

Can Someone Please Explain This Error - "runtime Error: Dictionary Size Changed During Iteration"?

def find_the_best_solution(shipping_request, list, current_solution, best_shipping_solution): if shipping_request == {}: return current_solution for item in shippi

Solution 1:

This has nothing to do with itertools.combinations, you are trying to change the structure of data you are iterating over, which is not allowed:

Runtime error: dictionary size changed during iteration

You are trying to add or delete keys from a dictionary as you iterate it. A workaround is to iterate over for key in list(dictionary) which makes a copy list of the dictionary's keys, so you can still modify the underlying dictionary, however you may also want to reconsider your general approach.

The lines causing the error are:

for item in shipping_request:

    for i inrange(0,len(list), 1):
            ...
            for x in combinations:
                ifsum(x) >= shipping_request[item]:
                    ifsum(x) > shipping_request[item]:
                        ...
                    temp_request = shipping_request
                    del temp_request[item] # you are trying to delete a key from # shipping_request as you iterate it

Perhaps you want to make a shallow copy eg. temp_request = dict(shipping_request) which makes a new dictionary with references to the same objects. However you may want a import copy; copy.deepcopy to recursively copy every object inside the dictionary.

Post a Comment for "Can Someone Please Explain This Error - "runtime Error: Dictionary Size Changed During Iteration"?"