类型错误:不可散列类型:'sl​​ice' [python] [dictionaries]

时间:2021-05-27 13:55:12

标签: python dictionary typeerror python-3.9

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

2 个答案:

答案 0 :(得分:1)

这是一个更好的方法:

import os

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

答案 1 :(得分:0)

如果您只想在 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

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