Search code examples
pythondictionaryhashhashlib

How to Store a Hashed String in a Dictionary


I am new to python and I am trying to store a hashed string in a dictionary. I don't know how to and have gotten no luck googling it, can anyone help me? Here is my code:

'''

  import hashlib

  has_account = input('Do you have an account already (Y or N)?: ')
  has_account = str.title(has_account)


  if has_account == 'N':
 new_user = {}
 new_username = input('Please create a username: ')
 new_password = input('Please enter a password at least 6 digits long: ')
 while len(new_password) < 6:
     new_password = input('Please enter a password at least 6 digits long: ')
  reentered_password = input('Please reenter you password: ')
  while new_password != reentered_password:
     print('Passwords are different, please renter both passwords')
      new_password = input('Please enter a password at least 6 digits long: ')
      while len(new_password) < 6:
         new_password = input('Please enter a password at least 6 digits long: ')
      reentered_password = input('Please reenter you password: ')

   buffer = new_password.encode('utf-8')
  hash_object = hashlib.sha1(buffer)
  buffer = hash_object.hexdigest()
  hashed_password = buffer
  del new_password, buffer, reentered_password
  new_user[new_user] = hashed_password
  del new_user, hashed_password

'''

it just outputs: "new_user[new_user] = hashed_password TypeError: unhashable type: 'dict'" The spacing may of gotten messed up by pasting it in here, here's a screen shot of the original code: enter image description here Thanks for any help in advance


Solution

  • The idea of a dictionary is that you associate a value with a key that you use to look it up, like how in a real dictionary you can look up a word (the key) to find its definition (the value).

    You got the error you did because you tried to use the entire dictionary itself as the key to look something up in it; this makes no sense and consequently does not work. You probably want to do something more like:

    new_user["password"] = hashed_password
    

    It's not obvious what this is useful for, but if all you're trying to do is "store a string in a dictionary" then this qualifies as that.