I'm new programming on python(2.x) and even looking for hours i couldn't solve the problem. Python returns a KeyError
The (object).csv file is:
id,name,type
1,low,player
The python code is:
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:
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. When i change the name of "id" column, the error returns to the new header (previously "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'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.