python dictionary changed size during iteration 解决方案

最近练手一个项目时,发现python中字典修改后再引用该字典会报:
dictionary changed size during iteration 的错误
如下:

def show_dic(site):
    	for key, value in site.items():
        if key == 'name':
            site.pop(key)
if __name__ == '__main__':
    web_site= {'name': 'Address', 'alexa': 54316, 'url':'http://blog.csdn.net/123/'}
    show_dic(web_site)
    for key, value in web_site.items():
        print(key, value)

python dictionary changed size during iteration 解决方案_第1张图片
原因是, 你修改了字典, 然后没有返回一个新字典。
修改如下:

   for key, value in site.items():
       if key == 'name':
           site.pop(key)
       return site    #多了这一句
if __name__ == '__main__':
   web_site= {'name': 'Address', 'alexa': 54316, 'url':'http://blog.csdn.net/123/'}
   show_dic(web_site)
   for key, value in web_site.items():
       print(key, value)

添加return后可运行

再有一种,就是我们不用 dic.items()去取, 用dic.keys()。根据keys再获取values
这里就不赘述了。因为第一种才是较好的方法。有兴趣的可以去思考下。
网上说可以转换成list再使用,有点不太明白转为list之后怎么取值。

你可能感兴趣的:(Python,dictionary)