将清单清单转换成字典

我在下面有一个文本文件:

A test B echo C delete
A test B echo C delete D modify
A test B echo C delete

我想解析上面的文本文件,转换为列表列表,然后转换为字典。

预期的清单清单是:

[['A', 'test', 'B', 'echo', 'C', 'delete'], ['A', 'test', 'B', 'echo', 'C', 'delete', 'D', 'modify'], ['A', 'test', 'B', 'echo', 'C', 'delete']]

字典的最终结果是:

[{'A':'test','B':'echo','C':'delete'},{'A':'test','B':'echo','C':'delete','D': 'modify'},{'A':'test', 'B':'echo', 'C':'delete'}]

这是我的脚本:

#!/usr/bin/python3

def listToDict(list):
    listDict = {list[i]: list[i + 1] for i in range (0, len(list), 2)}
    return listDict 

def parse_file(filepath):
    string_to_listoflist = []
    with open(filepath, 'r') as file_object:
        lines = file_object.readlines()
    for line in lines:
           string_to_listoflist.append(line.rstrip().split())

    dictionary = listToDict(string_to_listoflist)  
    print(dictionary)

if __name__ == '__main__':
    filepath = 'log.txt'
    parse_file(filepath)

上面的脚本将产生以下错误:

Traceback (most recent call last):
  File "parse.py", line 19, in <module>
    parse_file(filepath)
  File "parse.py", line 14, in parse_file
    dictionary = listToDict(string_to_listoflist)
  File "parse.py", line 4, in listToDict
    listDict = {list[i]: list[i + 1] for i in range (0, len(list), 2)}
  File "parse.py", line 4, in <dictcomp>
    listDict = {list[i]: list[i + 1] for i in range (0, len(list), 2)}
TypeError: unhashable type: 'list'

现在,我在下面的列表中创建另一个循环:

#!/usr/bin/python3

def listToDict(list):
    listDict = {list[i]: list[i + 1] for i in range (0, len(list), 2)}
    return listDict 

def parse_file(filepath):
    string_to_listoflist = []
    dictionary           = {}
    with open(filepath, 'r') as file_object:
        lines = file_object.readlines()
    for line in lines:
           string_to_listoflist.append(line.rstrip().split())

    for e in string_to_listoflist:
        dictionary = listToDict(e)  
    print(dictionary)

if __name__ == '__main__':
    filepath = 'log.txt'
    parse_file(filepath)

即使我在循环之前定义了dictionary变量,上面的脚本也会产生意外的结果:

{'A': 'test', 'B': 'echo', 'C': 'delete'}

然后如下更改打印命令的位置:

#!/usr/bin/python3

def listToDict(list):
    listDict = {list[i]: list[i + 1] for i in range (0, len(list), 2)}
    return listDict 

def parse_file(filepath):
    string_to_listoflist = []
    dictionary           = {}
    with open(filepath, 'r') as file_object:
        lines = file_object.readlines()
    for line in lines:
           string_to_listoflist.append(line.rstrip().split())

    for e in string_to_listoflist:
        dictionary = listToDict(e)  
        print(dictionary)

if __name__ == '__main__':
    filepath = 'log.txt'
    parse_file(filepath)

上面的脚本的意外结果是:

{'A': 'test', 'B': 'echo', 'C': 'delete'}
{'A': 'test', 'B': 'echo', 'C': 'delete', 'D': 'modify'}
{'A': 'test', 'B': 'echo', 'C': 'delete'}

谁能帮助解决我的问题?

谢谢

评论