How To Solve Dictionary Changed Size During Iteration Error?
Solution 1:
In Python3, Try
for key in list(dict.keys()):
if condition:
matched
del dict[key]
1 more thing should be careful when looping a dict to update its key:
Code1:
keyPrefix = ‘keyA’
for key, value in Dict.items():
newkey = ‘/’.join([keyPrefix, key])
Dict[newkey] = Dict.pop(key)
Code2:
keyPrefix = ‘keyA’
for key, value in Dict.keys():
newkey = ‘/’.join([keyPrefix, key])
Dict[newkey] = Dict.pop(key)
Result of code1/code2 is:
{‘keyA/keyA/keyB’ : ”, ‘keyA/keyA/keyA’: ”}
My way to resolve this unexpected result:
Dict = {‘/’.join([keyPrefix, key]): value for key, value in Dict.items()}
Link: https://blog.gainskills.top/2016/07/21/loop-a-dict-to-update-key/
Solution 2:
Alternative solutions
If you're looking for the smallest value in the dictionary you can do this:
min(dictionary.values())
If you cannot use min, you can use sorted:
sorted(dictionary.values())[0]
Why do I get this error?
On a side note, the reason you're experiencing an Runtime Error
is that in the inner loop you modify the iterator your outer loop is based upon. When you pop
an entry that is yet to be reached by the outer loop and the outer iterator reaches it, it tries to access a removed element, thus causing the error.
If you try to execute your code on Python 2.7 (instead of 3.x) you'll get, in fact, a Key Error
.
What can I do to avoid the error?
If you want to modify an iterable inside a loop based on its iterator you should use a deep copy of it.
Solution 3:
You can use copy.deepcopy to make a copy of the original dict, loop over the copy while change the original one.
from copy import deepcopy
d=dict()
for i in range(5):
d[i]=str(i)
k=deepcopy(d)
d[2]="22"
print(k[2])
#The result will be 2.
Your problem is iterate over something that you are changing.
Solution 4:
Record the key during the loop and then do dictionary.pop(key) when loop is done. Like this:
for key,value in dictionary.items():
for key1, value1 in dictionary.items():
if key1!= key and value > value1:
storedvalue = key
dictionary.pop(key)
Solution 5:
Here is one way to solve it:
- From the dictionary, get a list of keys, sorted by value
- Since the first key in this list has the smallest value, you can do what you want with it.
Here is a sample:
# A list of grades, not in any order
grades = dict(John=95,Amanda=89,Jake=91,Betty=97)
# students is a list of students, sorted from lowest to highest grade
students = sorted(grades, key=lambda k: grades[k])
print 'Grades from lowest to highest:'
for student in students:
print '{0} {1}'.format(grades[student], student)
lowest_student = students[0]
highest_student = students[-1]
print 'Lowest grade of {0} belongs to {1}'.format(grades[lowest_student], lowest_student)
print 'Highest grade of {0} belongs to {1}'.format(grades[highest_student], highest_student)
The secret sauce here is in the sorted() function: instead of sorting by keys, we sorted by values.
Post a Comment for "How To Solve Dictionary Changed Size During Iteration Error?"