简体   繁体   中英

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

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 -

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 . To fetch it, the key (ie "{}": ant[i]... ) is hashed first. So, python is throwing the error.

You can remove dict_number from your code as it is always i + 1. This can be done using enumerate and for loop.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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