Python appending dictionary, TypeError: unhashable type?
abc = {}
abc[int: another开发者_运维百科int]
Then the error came up. TypeError: unhashable type? Why I received this? I've tried str()
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.
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
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]}
精彩评论