KeyError Filling Defaultdict Python

KeyError Filling Defaultdict Python

我正在尝试用 csv 数据填充默认字典,但出现了键错误

for i in range(0,1):

    #https://docs.python.org/2/library/collections.html#collections.defaultdict
    result = co.defaultdict(list)
    with open(os.path.join(inputdir,tablelist[i])) as f:

        csv_reader = csv.reader(f)
        csv_headings = next(csv_reader)
        read = csv.DictReader(f)

        for line in read:
            for j in range(1,len(csv_headings)):
  error here--->result[line[csv_headings[0]]].append(line[csv_headings[j]])  

对于 csv 数据

API,CNTYNM,PRMT,
4700100002,Barbour,2,
4700100003,Barbour,3,
4700100004,Barbour,4,

关键错误是 API,这对我来说意味着 dictreader 的某些功能无法按预期工作,有人可以提供一些建议吗?

您缺少 DictReaderfieldnames 参数。如果您修改代码以将 csv_haedings 传递给 DictReader,它将起作用(希望如预期的那样):

for i in range(0,1):

    #https://docs.python.org/2/library/collections.html#collections.defaultdict
    result = co.defaultdict(list)
    with open(os.path.join(inputdir,tablelist[i])) as f:

        csv_reader = csv.reader(f)
        csv_headings = next(csv_reader)
        read = csv.DictReader(f, fieldnames=csv_headings)

        for line in read:
            for j in range(1,len(csv_headings)):
                result[line[csv_headings[0]]].append(line[csv_headings[j]])