在CSV文件中存在密钥时出现KeyError



我得到了KeyError: 'District'但是我的文件中有District列这里是

代码:

# Create the CSV file: csvfile
csvfile = open('crime_sampler.csv', 'r')
# Create a dictionary that defaults to a list: crimes_by_district
crimes_by_district = defaultdict(list)
# Loop over a DictReader of the CSV file
for row in csv.DictReader('crime_sampler.csv'):
# Pop the district from each row: district
district = row.pop('District')
# Append the rest of the data to the list for proper district in crimes_by_district
crimes_by_district[district].append(row)

错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/tmp/ipykernel_608/747227460.py in <cell line: 8>()
8 for row in csv.DictReader('crime_sampler.csv'):
9     # Pop the district from each row: district
---> 10     district = row.pop('District')
11     # Append the rest of the data to the list for proper district in crimes_by_district
12     crimes_by_district[district].append(row)
KeyError: 'District'

从https://docs.python.org/3/library/csv.html,我相信你应该将参数更改为csv.DictReader():

# Create the CSV file: csvfile
csvfile = open('crime_sampler.csv', 'r')
# Create a dictionary that defaults to a list: crimes_by_district
crimes_by_district = defaultdict(list)
# Loop over a DictReader of the CSV file
for row in csv.DictReader(csvfile):
# Pop the district from each row: district
district = row.pop('District')
# Append the rest of the data to the list for proper district in crimes_by_district
crimes_by_district[district].append(row)

最新更新