无法更新字典中的值 - 字典。改变了大小

时间:2017-06-22 22:53:22

标签: python-3.x

我循环使用CSV,并希望更改" Gotham"到" Home"。我在网上搜索后尝试了几种方法,但似乎无法让它发挥作用。

import csv

csv_file = "test.csv"

def process_csv(file):
    headers=[]
    data = []
    csv_data = csv.reader(open(file))
    for i, row in enumerate(csv_data):
        if i == 0:
            headers = row
            continue;
        field = []
        for i in range(len(headers)):
            field.append((headers[i],row[i]))
        data.append(field)
    return data

def create_merge_fast(city, country, contact):
    lcl = locals()

    ## None of these do what I'd think - if city is "Gotham" change it to "Home"
    for key, value in lcl.items():
        if value == "Gotham":
            lcl[value] = "Home"
        print(key, value)

    for value in lcl.values():
        if value == "Gotham":
            lcl[value] = "Home"
        print(value)

def set_fields_create_doc(data):
    city = data[4][1]
    country = data[6][1]
    contact = data[9][1]
    create_merge_fast(city, country, contact)

data = process_csv(csv_file)

for i in data:
    set_fields_create_doc(i)

我似乎总是得到

  

RuntimeError:字典在迭代期间改变了大小

之后 Gotham 印刷...

2 个答案:

答案 0 :(得分:1)

更改

lcl[value] = "Home"

lcl[key] = "Home"

前者实际上会在您的字典中创建一个新条目,其密钥为"Gotham",值为"Home",而不是将现有值从"Gotham"修改为"Home"

所以,你想要:

for key in lcl:
    if lcl[key] == "Gotham":
        lcl[key] = "Home"
    print(key, lcl[key])

另外,你不需要第二次循环。

答案 1 :(得分:1)

在迭代它时你不能改变你的dict - 当你改变它的状态时,for..in循环中的迭代器变得无效,所以它会从标题中弹出错误。

您可以通过在找到匹配后停止迭代并对dict进行更改来简单地解决这个问题,即

for key, value in lcl.items():
    if value == "Gotham":
        lcl[key] = "Home"
        break  # exit here
    print(key, value)

但是,如果可能有多个符合此条件的项目,那么简单地删除将无效,但您可以在开始迭代之前冻结密钥列表:

for key in list(lcl.keys()):
    if lcl[key] == "Gotham":
       lcl[key] = "Home"