[英]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.