简体   繁体   English

类型错误:不可散列类型:'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
 

Error:错误:

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

Can you help me to solve this, please?你能帮我解决这个问题吗? I am using Windows x64我正在使用 Windows x64

Here is a better way to do it:这是一个更好的方法:

import os

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

If you want to just add an entry in dictionary with dict_number as key and ant[i] as value, you can just do -如果您只想在dictionary中添加一个条目,其中dict_number作为键, ant[i]作为值,您可以这样做 -

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

The problem in your code dictionary["{}": ant[i].format(dict_number)] is that "{}": ant[i].... is treated as a slice and that is used to fetch value from dictionary .您的代码dictionary["{}": ant[i].format(dict_number)]中的问题是"{}": ant[i]....被视为一个切片,用于从中获取值dictionary To fetch it, the key (ie "{}": ant[i]... ) is hashed first.要获取它,首先对密钥(即"{}": ant[i]... )进行哈希处理。 So, python is throwing the error.因此, python 抛出错误。

You can remove dict_number from your code as it is always i + 1. This can be done using enumerate and for loop.您可以从代码中删除dict_number ,因为它始终为i + 1。这可以使用enumerate和 for 循环来完成。

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

Here enumerate returns the index as well as the element of the list ant and start=1 will enforce that the index will start from 1.这里enumerate返回索引以及列表ant的元素,并且start=1将强制索引从 1 开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM