RuntimeError dictionary changed size during iteration 遍历字典时报错

RuntimeError: dictionary changed size during iteration

在字典遍历过程中修改字典长度时会报错;这里是遍历时修改了字典长度,导致了字典中有字典,一直在查找,直到RuntimError。


我是在用globals函数时,发现的问题:

# test.py
# version:Python3.6.0
def test1():
    pass

class Test2(object):
    def test3(self):
        pass

g_dict = globals()
# print(g_dict)

for key in (g_dict.keys()):
    print(f'{key}:{g_dict[key]}')

应该使用list将dict变为列表,才能遍历。

for key in list(g_dict.keys()):  
    print(f'{key}:{g_dict[key]}')

仔细一想,我在遍历时好像没有改变字典元素呀,原因在哪里?看了打印结果才感觉发现是globals()这个函数的原因:

打印结果:

__name__:__main__
__doc__:None
__package__:None
__loader__:<_frozen_importlib_external.SourceFileLoader object at 0x000001ED473AC240>
__spec__:None
__annotations__:{}
__builtins__:<module 'builtins' (built-in)>
__file__:D:/keeplearning/myLearning/python/book2/test.py
__cached__:None
test1:<function test1 at 0x000001ED472A3E18>
Test2:<class '__main__.Test2'>
g_dict:{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001ED473AC240>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/keeplearning/myLearning/python/book2/test.py', '__cached__': None, 'test1': <function test1 at 0x000001ED472A3E18>, 'Test2': <class '__main__.Test2'>, 'g_dict': {...}, 'key': 'g_dict'}

发现g_dict键的值中有递归了,g_dict的值中出现了’g_dict’: {…} 。

修改如下:

for key in list(g_dict.keys()):
    if not isinstance(g_dict[key],dict):
        print(f"{key}:{g_dict[key]}")

结果:

__name__:__main__
__doc__:None
__package__:None
__loader__:<_frozen_importlib_external.SourceFileLoader object at 0x00000217DCB3C240>
__spec__:None
__builtins__:<module 'builtins' (built-in)>
__file__:D:/keeplearning/myLearning/python/book2/test.py
__cached__:None
test1:<function test1 at 0x00000217DCA33E18>
Test2:<class '__main__.Test2'>

globals() 返回一个字典,表示当前的全局符号表。这个符号表始终针对当前模块(对函数或方法来说,是指定义它们的模块,而不是调用它们的模块)。

发布了87 篇原创文章 · 获赞 43 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_31362767/article/details/103267634
今日推荐