【问题标题】:Unable to create a dictionary无法创建字典
【发布时间】:2015-09-28 04:42:09
【问题描述】:

我正在尝试编写一个用于日志解析的脚本。 我有一个文件,其中的日志杂乱无章。特定日志的每一行都会有时间戳,所以我想使用它对它们进行排序。

例如

10:48 开始 . . 10:50 开始 . . 10:42 开始 第一行将包含关键字“开始”和时间戳。 “开始”和下一个“开始”之前的线是一组。我想根据时间戳对日志文件中的所有这些集合进行排序。

代码逻辑: 我想创建字典,我将在其中选择这个时间并将其分配为“键”和该日志集的值中的文本。然后我将对字典中的“键”进行排序,并在文件中按排序顺序打印它们的“值”。 但是我收到错误“TypeError: unhashable type: 'list'”

write1 = False
x = 0
search3 = "start"
matched = dict()
matched = {}

# fo is a list which is defined elsewhre in the code.

for line in fo:

    if search3 in line:

    #got the Hello2 printed which indicates script enters this loop

        print('hello2')
        write1 = True
        x +=1
        time = line.split()[3]
        name1 = [time.split(':')[0] +":"+time.split(':')[1] + ":"+     time.split(':')[2]]
        matched[name1] = line

    elif write1:
        matched[name1] += line

print(matched.keys())

请告诉我我的逻辑和我的做法是否正确?

【问题讨论】:

  • dict 键不应该是一个列表。 “name1”在此处列出。将其设为字符串或元组。

标签: python dictionary


【解决方案1】:

您将name1 设置为列表。列表不是可散列的,只有元组是。但是,我假设您希望 name1 是一个字符串,所以您只想删除括号:

name1 = time.split(':')[0] +":"+time.split(':')[1] + ":"+     time.split(':')[2] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多