KeyError填充Defaultdict Python

时间:2016-02-29 18:00:50

标签: python dictionary defaultdict

我正在尝试用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没有按预期工作,任何人都可以给出一些建议吗?

1 个答案:

答案 0 :(得分:2)

你遗漏了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]])