Type Error : Unhashable type: 'slice' [python] [dictionaries]

Type Error : Unhashable type: 'slice' [python] [dictionaries]

os.chdir("Güvenlik_Hesaplar")
files = ''
dictionary = {}
ant = os.listdir()
dict_number = 1
i = 0 

while i < len(ant): # If the variable 'i' is less than the length of my files
    dictionary["{}" : ant[i].format(dict_number)] #e.g = '1': 'myfile.txt'
    dict_number += 1
    i += 1
 

错误:

 File "C:\Users\Barış\Desktop\Python\prg.py", line 20, in passwordrequest
 dictionary["{}" : ant[i].format(dict_number)]
 TypeError: unhashable type: 'slice'

你能帮我解决这个问题吗?我正在使用 Windows x64

这里有一个更好的方法:

import os

os.chdir("Güvenlik_Hesaplar")
dictionary = {str(k + 1): filename for k, filename in enumerate(os.listdir())}

如果你只想在 dictionary 中添加一个条目,其中 dict_number 作为键,ant[i] 作为值,你可以只做 -

while i < len(ant):
    dictionary[str(dict_number)] = ant[i]
    ....

您的代码 dictionary["{}" : ant[i].format(dict_number)] 中的问题是 "{}" : ant[i].... 被视为一个切片,用于从 dictionary 获取值。要获取它,首先对密钥(即 "{}" : ant[i]...)进行哈希处理。所以,python 抛出错误。

您可以从代码中删除 dict_number,因为它始终是 i + 1。这可以使用 enumerate 和 for 循环来完成。

for dict_number, file in enumerate(ant, start=1):
    dictionary[str(dict_number)] = file

此处enumeratereturns索引以及列表的元素antstart=1将强制索引从1开始。