Issue
Is it possible to iterate through a dictionary while updating a separate dictionary? I tried to create a copy of my original dictionary and edit that one but I'm still getting an error
d = {30:3, 54:5, 16:2}
r = d
for k,v in d.items():
biggest = max(d,key = d.get)
del(r[biggest])
I need to find the largest value of the dictionary each time it loops through. Then I need to remove that item from the dictionary so I can find the next largest item.
The error I get when I run this code is as follows.
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
for k,v in d.items():
RuntimeError: dictionary changed size during iteration
Solution
You are actually iterating over the same dictionary since r = d
does not creates a new dictionary. r
is just another reference to the same dictionary. You can check the object identities to confirm that:
>>> r = d
>>> r is d
True
Please, see this discussion for more details about object identity:
"is" operator behaves unexpectedly with integers
So, the right thing to do is first create a copy of the dictionary and then alter it:
>>> r = d.copy()
>>> r is d
False
And the iteration:
for k,v in d.items():
biggest = max(d,key = d.get)
del(r[biggest])
So, from your code we just need to change a single line:
d = {30:3, 54:5, 16:2}
r = d.copy() # changed: use copy here
for k,v in d.items():
biggest = max(d,key = d.get)
del(r[biggest])
Answered By - marcospereira
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.