0

我正在尝试使用新键将一个值拆分为三个不同的值并将它们添加到我的字典中。但我总是收到错误消息: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]

但我无法更改密钥或添加新密钥。我究竟做错了什么?

4

1 回答 1

0

固定的:

    for row in reader:
        students.append(row)
    for i in range(len(students)):
        name = students[i].get('name')
        name = name.split()
        if len(name) == 3:
            students[i]['first'] = name[0]
            students[i]['middle'] = name[1]
            students[i]['last'] = name[2]
            students[i].pop('name')
        else:
            students[i]['first'] = name[0]
            students[i]['middle'] = None
            students[i]['last'] = name[1]
            students[i].pop('name')
    return students

这部分似乎是多余的并导致问题,但我不知道为什么:

        for k, v in students[i].items():
            if k == 'name':
于 2020-06-26T06:29:39.437 回答