程序提示KeyError: 'col5',修改程序new_data = [] for row in data2: new_data.append({'col1': row['col1'], 'col2': row['col2'], 'col3': row['col3'], 'col4': row.get('col4', 0)}) # 将新的数据列表写入新的csv文件中 with open('result_2.txt', 'w', newline='') as f: writer = csv.writer(f) for row in new_data: writer.writerow(["{}\t{}\t{}\t{}\t{}".format(row['col1'], row['col2'], row['col3'], row['col4'], row['col5'])])
时间: 2023-09-16 20:07:40 浏览: 134
如果提示KeyError: 'col5',说明在new_data列表中的某些字典中不存在'col5'键,而在输出结果时却尝试使用'col5'键。您可以通过在new_data列表中添加默认值来解决这个问题,或者在写入文件时使用字典的get方法来获取'col5'键对应的值。以下是两种修改方案:
方案1:在new_data列表中添加默认值
```
new_data = []
for row in data2:
new_row = {'col1': row['col1'], 'col2': row['col2'], 'col3': row['col3'], 'col4': row.get('col4', 0), 'col5': 0}
new_data.append(new_row)
for query in data1:
for row in new_data:
if row['col1'] == query['col1'] and row['col2'] == query['col2']:
row['col5'] = query['col3']
with open('result_2.txt', 'w', newline='') as f:
writer = csv.writer(f)
for row in new_data:
writer.writerow(["{}\t{}\t{}\t{}\t{}".format(row['col1'], row['col2'], row['col3'], row['col4'], row['col5'])])
```
在上面的程序中,我们在new_data列表中添加了一个默认值0,以确保在new_data列表中的每个字典中都包含'col5'键。在对new_data列表进行遍历时,如果找到了与data1列表中的查询点匹配的行,则将'col5'键的值赋值为查询结果。
方案2:使用字典的get方法获取'col5'键的值
```
new_data = []
for row in data2:
new_row = {'col1': row['col1'], 'col2': row['col2'], 'col3': row['col3'], 'col4': row.get('col4', 0)}
new_data.append(new_row)
for query in data1:
for row in new_data:
if row['col1'] == query['col1'] and row['col2'] == query['col2']:
row['col5'] = query['col3']
with open('result_2.txt', 'w', newline='') as f:
writer = csv.writer(f)
for row in new_data:
writer.writerow(["{}\t{}\t{}\t{}\t{}".format(row['col1'], row['col2'], row['col3'], row['col4'], row.get('col5', ''))])
```
在上面的程序中,我们使用了字典的get方法来获取'col5'键对应的值。如果某个字典中不存在'col5'键,那么get方法会返回一个空字符串,从而避免了KeyError异常的出现。
阅读全文