【问题标题】:Type Error : Unhashable type: 'slice' [python] [dictionaries]类型错误:不可散列类型:'sl​​ice' [python] [dictionaries]
【发布时间】:2021-08-15 19:16:48
【问题描述】:
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

【问题讨论】:

  • 您尝试插入dictionary,键为dict_number,值为ant[i]?然后就做dictionary[str(dict_number)] = ant[i]。您也可以删除dict_number,因为它始终是i + 1

标签: python dictionary typeerror python-3.9


【解决方案1】:

这是一个更好的方法:

import os

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

【讨论】:

    【解决方案2】:

    如果你只想在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开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      相关资源
      最近更新 更多