首页 > 解决方案 > 如何将元素添加到字典中的列表中?

问题描述

我一直在努力完成这项工作,也许我在这里遗漏了一些东西。

以下代码的目的是将在 CSV 的每一行的第 1 列中找到的值添加到字典中,该字典在第二 (1) 位置连续一个列表,以便将新值附加到列表中而不是覆盖每个在 CSV 上找到相同密钥的时间(因为相同的密钥出现多次重复)。

csr = {} 
    with open('RawPolicy.csv', newline='') as rulemaker:
        rmatcher = csv.reader(rulemaker, delimiter=" ")

        for row in rmatcher:
            lst = []        
            csr[row[6]]=[row[0],lst.append(row[1]),row[2],row[3],row[4],row[5]]

但我总是收到以下错误,这对我来说毫无意义,因为缩进对我来说似乎没问题。

当我从 for 循环内部删除列表(lst)和“lst.append(row [1])”部分时,脚本可以工作,但没有做我想要的。

csr[row[6]]=[row[0],lista.append(row[1]),row[2],row[3],row[4],row[5]]

TabError: inconsistent use of tabs and spaces in indentation

标签: pythonpython-3.x

解决方案


您的with块缩进太远。它应该是:

csr = {} 
with open('RawPolicy.csv', newline='') as rulemaker:
    rmatcher = csv.reader(rulemaker, delimiter=" ")

    for row in rmatcher:
        lst = []        
        csr[row[6]]=[row[0],lst.append(row[1]),row[2],row[3],row[4],row[5]]

推荐阅读