-1
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

kuro
  • 3,214
  • 3
  • 15
  • 31
Baris_Ertan
  • 23
  • 1
  • 5
  • 1
    You are trying to insert into `dictionary` with key as `dict_number` and value as `ant[i]`? Then just do `dictionary[str(dict_number)] = ant[i]`. Also you can remove `dict_number` as it is always `i` + 1 – kuro May 27 '21 at 13:58

2 Answers2

1

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())}
JMA
  • 803
  • 4
  • 9
0

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.

kuro
  • 3,214
  • 3
  • 15
  • 31