Traceback (most recent call last):
File "/home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py", line 18, in
for key, value in dict_data.items():
RuntimeError: OrderedDict mutated during iteration
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# yongqiang cheng
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
dict_data = OrderedDict()
dict_data['1'] = "cheng"
dict_data['2'] = "yong"
dict_data['3'] = "qiang"
dict_data['4'] = "forever"
dict_data['5'] = "strong"
for key, value in dict_data.items():
print(key + ': ' + value)
if ('3' == key):
del dict_data[key]
/home/yongqiang/miniconda3/envs/pt-1.4_py-3.6/bin/python /home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py
Traceback (most recent call last):
File "/home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py", line 18, in
for key, value in dict_data.items():
RuntimeError: OrderedDict mutated during iteration
1: cheng
2: yong
3: qiang
Process finished with exit code 1
dict_data.items()
does not return a copy, so it should not be modified while iterating.Python 中赋值语句不复制对象,而是在目标和对象之间创建绑定 (bindings) 关系。对于自身可变或者包含可变项的集合对象,开发者有时会需要生成其副本用于改变操作,进而避免改变原对象。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# yongqiang cheng
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
dict_data = OrderedDict()
dict_data['1'] = "cheng"
dict_data['2'] = "yong"
dict_data['3'] = "qiang"
dict_data['4'] = "forever"
dict_data['5'] = "strong"
for key, value in list(dict_data.items()):
print(key + ': ' + value)
if ('3' == key):
del dict_data[key]
print()
for key, value in list(dict_data.items()):
print(key + ': ' + value)
/home/yongqiang/miniconda3/envs/pt-1.4_py-3.6/bin/python /home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py
1: cheng
2: yong
3: qiang
4: forever
5: strong
1: cheng
2: yong
4: forever
5: strong
Process finished with exit code 0