读取excel svc并将结果列表转换为字典

我有几天的search,我怎么能做到这一点,我不能解决这个问题。 我看到了太多关于我会做什么的信息,但是我无法解决我的问题(对于我的不好的补充)。

我会从Excel中读取值,然后将其插入到字典中。

为了做到这一点,我从一个csv excel中读取,并将其插入到字典中,我读取行并将其插入到列表中,当所有列表都被放入字典中时,我就有了这个文件(excel):

action key turn on TO001 turn off TO000 conect CO001 disconect DI000 plug PO001 unplug UP000 

我的代码读取CSV文件是:

 def __call__(self, fileToRead): print("\n Now the output from a dictionary created from the csv file") try: with open(Read.ROUTE+fileToRead+Read.EXT, 'rt') as mycsvfile: dictioData = csv.DictReader(mycsvfile, dialect='excel') for row in dictioData: Read.list.append(row) print(row) except FileNotFoundError as error: if error.errno == errno.ENOENT: print ("File not found, please check the name and try again") Dicctionary.setVerbs(self,Read.list) 

在这一部分,我有一个问题,我会读取值:

 'turn on' : 'TO001' 'turn off' : 'TO000' ... 

但是它写道:

 {'action;key': 'turn on ;TO001'} {'action;key': 'turn off ;TO000'} ... 

我怎样才能做到这一点?

谢谢。

那么,你过分复杂这一个。 如果你能够将你的Excel文件转换成.csv文件:

 action;key turn on;TO001 turn off;TO000 conect;CO001 disconect;DI000 plug;PO001 unplug;UP000 

你也许可以做这样的事情:

 def csv_to_dict(filename): with open(filename) as f: d = {} # create an empty dictionary where we'll add the data for row in csv.DictReader(f, delimiter=';'): # iterate over DictReader object d[row['action']] = row['key'] # add data to the dictionary the way we want return d # return the data if __name__ == '__main__': filename = 'path_to_file_here' # here complete the path pprint(csv_to_dict(filename)) # I've used pprint to have the dictionary nicely printed 

哪个会打印你想要的:

 {'conect': 'CO001', 'disconect': 'DI000', 'plug': 'PO001', 'turn off': 'TO000', 'turn on': 'TO001', 'unplug': 'UP000'}