Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python appending dictionary, TypeError: unhashable type?

abc = {}
abc[int: anotherint]

Then the error came up. TypeError: unhashable type? Why I received this? I've tried str()

like image 684
user469652 Avatar asked Oct 14 '10 00:10

user469652


3 Answers

This seems to be a syntax issue:

>>> abc = {}
>>> abc[1] = 2
>>> abc
{1: 2}
>>> abc = {1:2, 3:4}
>>> abc
{1: 2, 3: 4}
>>> 

At least the syntax of following is incorrect

abc[int: anotherint]

I guess you want to say

abc = [int: anotherint]

Which is incorrect too. The correct way is

abc = {int: anotherint}

unless abc is already defined in which case:

abc[int] = anotherint

is also a valid option.

like image 148
pyfunc Avatar answered Nov 17 '22 06:11

pyfunc


There are two things wrong - first you have a logic error - I really don't think you want the slice of the dictionary between int (the type, which is unhashable [see below]) and the number anotherInt. Not of course that this is possible in python, but that is what you are saying you want to do.

Second, assuming you meant x[{int:anotherInt}]:

What that error means is that you can't use that as a key in a dictionary, as a rule python doesn't like you using mutable types as keys in dictionaries - it complicates things if you later add stuff to the dictionary or list... consider the following very confusing example:

x={}
x[x]=1

what would you expect this to do, if you tried to subscript that array which would you expect to return 1?

x[{}]
x[{x:x}]
x[{{}:x}]
x[x]

basicly when hashing mutable types you can either say, {} != {} with respect to hashes because they are stored in different places in memory or you end up with the weird recursive situation above

like image 23
tobyodavies Avatar answered Nov 17 '22 05:11

tobyodavies


Since the title says appending and none of the answers provided a solution to append things to the dictionary I give it a try:

abc = {}
abc[1]= 2
abc['a'] = [3,9,27]
==> abc = {1:2, 'a':[3,9,27]}
like image 1
v.tralala Avatar answered Nov 17 '22 07:11

v.tralala