[Tutor] TypeError: dict objects are unhashable

Kent Johnson kent37 at tds.net
Fri Mar 24 17:31:03 CET 2006


Ben Vinger wrote:
> Hello
> 
> I want to create a dictionary (from SQL usernames) of
> the format:
>       accounts = {
>       ('psmit', '123456'): 'psmit',
>       ('rmatt', 'mypass'): 'rmatt',
>       }
> 
> So I have:
>       accounts = {}
>       UserCursor.execute(sqlstr)
>       rows = UserCursor.fetchall()
>       UserConn.commit()
>       for row in rows:
>             U = row['User']
>             P = row['Password']
>             InnerDict = {}
>             InnerDict[U] = P
>             accounts[InnerDict] = U
> 
> But I get:
> TypeError: dict objects are unhashable
> Unfortunately, I just can't see what I'm doing wrong

You are trying to use a dictionary as the key to your dictionary. This 
doesn't work - dicts can't be used as dict keys, which is what the error 
message is trying to tell you.

Instead of
       accounts = {
       ('psmit', '123456'): 'psmit',
       ('rmatt', 'mypass'): 'rmatt',
       }

your code tries to make
       accounts = {
       {'psmit': '123456'}: 'psmit',
       {'rmatt': 'mypass'}: 'rmatt',
       }

try this
             accounts[U, P] = U

though I'm not sure why you use a dict instead of a set here, since the 
value is contained in the key.

Kent



More information about the Tutor mailing list