我正在尝试使用新键将一个值拆分为三个不同的值并将它们添加到我的字典中。但我总是收到错误消息:RuntimeError: OrderedDict mutated during iteration
def csv_to_dic(file):
with open(file, "r") as csvfile:
# creat object, that can read csv as dictionary (including key)
reader = csv.DictReader(csvfile)
# define students as mutable list of dictionary rows
students = []
# read each row in file and save into students (load everything into memory)
for row in reader:
students.append(row)
for i in range(len(students)):
for k, v in students[i].items():
if k == 'name':
string = v.split()
students[i].update({'first' : string[0]})
students[i].update({'middle' : string[1]})
students[i].update({'last' : string[2]})
return students
我可以看到,我可以像这样更改键的值:
if k == 'name':
string = v.split()
students[i][k] = string[0]
但我无法更改密钥或添加新密钥。我究竟做错了什么?