[英]Python returns KeyError in csv.DictReader()
I'm new programming on python(2.x) and even looking for hours i couldn't solve the problem. 我是python(2.x)上的新程序,甚至连数小时我都无法解决问题。 Python returns a KeyError Python返回KeyError
The (object).csv file is: (object).csv文件为:
id,name,type
1,low,player
The python code is: python代码是:
import csv
class Item(object):
def setup(self, config):
self.config = config
self.label = config['label']
self.name = config['name']
self.type = config['type']
def create_item(config):
new_item = Item()
new_item.setup(config)
return(new_item)
def populate():
all_items = {}
f = open('object.csv', 'rb')
reader = csv.DictReader(f, delimiter = ',')
for row in reader:
new_item = (create_item(row))
all_items[new_item.label] = new_item
return(all_items)
Python returns: Python返回:
Self.type = config['type']
KeyError: 'type'
The weird thing is that both in csv and in the python code the column header doesn't contain any typing error. 奇怪的是,在csv和python代码中,列标题均不包含任何键入错误。 When i change the name of "id" column, the error returns to the new header (previously "id"). 当我更改“ id”列的名称时,错误返回到新标题(以前为“ id”)。 (The same happens when i add another header and try to read it) (当我添加另一个标题并尝试读取它时,也会发生同样的情况)
Any help is welcome and sorry for the inconvenience. 欢迎任何帮助,不便之处,敬请原谅。 grateful 感激
class Item(object):
def setup(self, config):
self.config = config
self.id = config['id']
self.name = config['name']
self.type = config['type']
def create_item(config):
new_item = Item()
new_item.setup(config)
return(new_item)
def populate():
all_items = {}
f = open('test.txt', 'r')
reader = csv.DictReader(f, delimiter = ',')
for row in reader:
new_item = (create_item(row))
all_items[new_item.id] = new_item
return(all_items)
output: 输出:
things = populate()
things.keys()
dict_keys(['1'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.