[英]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
这里enumerate
返回索引以及列表ant
的元素,并且start=1
将强制索引从 1 开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.