我是python(2.x)上的新编程,甚至找几个小时我都解决不了问题。 Python返回KeyError
(对象).csv文件是:
id,name,type
1,low,player
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返回:
Self.type = config['type']
KeyError: 'type'
奇怪的是,在csv和python代码中,列标题都不包含任何输入错误。 当我更改“id”列的名称时,错误将返回到新标题(以前为“id”)。 (当我添加另一个标题并尝试阅读时会发生同样的情况)
欢迎任何帮助,不便之处,敬请原谅。 感谢
答案 0 :(得分:0)
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)
输出:
things = populate()
things.keys()
dict_keys(['1'])