【问题标题】:Read excel svc and convert the resultat list to dictionary [Python]读取 excel svc 并将结果列表转换为字典 [Python]
【发布时间】:2016-11-18 08:48:26
【问题描述】:

我花了几天时间寻找如何做到这一点,但我无法解决。我看到太多关于我会做什么的信息,但我无法解决我的问题(抱歉我的理解不好)。

我会从 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")
    Dictionary.setVerbs(self,Read.list)

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

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

但上面写着:

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

我该怎么做?

谢谢。

【问题讨论】:

    标签: python excel python-3.x csv dictionary


    【解决方案1】:

    好吧,你把这件事弄得太复杂了。如果您能够将您的 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'}
    

    【讨论】:

    • 是的,这正是我想要的,非常感谢!! PS:漂亮的昵称!! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 2010-09-17
    • 1970-01-01
    • 2015-11-14
    • 2016-10-25
    • 2022-12-04
    相关资源
    最近更新 更多