В чем разница в Python между исключением «размер словаря изменился во время итерации» и «ключи словаря изменились во вреPython

Программы на Python
Гость
В чем разница в Python между исключением «размер словаря изменился во время итерации» и «ключи словаря изменились во вре

Сообщение Гость »


I am preparing a material about how iterators work in Python and I am currently working on a part about what happens if you change the dictionary you are iterating over. I know and added it to my material that it is bad practice, but I still wanted to try to see what happens.

The code below printed the key 5 and gave me a "dictionary changed size during iteration" exception. So I got the exception the moment I had a change and wanted to go to the next one.

d = {5:5, 10:10, 15:15, 20:20} for elem in d: print(elem) d[elem+1] = elem+1 This is OK. But then it occurred to me, what if I do both an add and a remove, so that the size technically, does not change. So I wrote this:

d = {5:5, 10:10, 15:15, 20:20, 25:25, 30:30, 35:35} for elem in d: print(elem) del d[elem] d[elem+1] = elem+1 It prints as many keys as elements in the dictionary (7), some of them being already the newly added values, but after printing 7 values it throws a "dictionary keys changed during iteration" exception. And now I am really curious what happens internally, that leads to this. I still know it is bad practice, I just want to understand it. Thanks!


Источник: https://stackoverflow.com/questions/781 ... ng-iterati

Вернуться в «Python»