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
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 (i.e. "{}" : 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.