Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a bytearray as a key to a dictionary

I am getting this error while adding a bytearray as a key to a dictionary:

TypeError: unhashable type: 'bytearray'

Here is the code:

str_dict = {}
s = bytearray(10)

for x in range(0, 10):
    value = get_str(s)
    str_dict[s] = value

So I create a bytearray and the function get_str(s) updates the s and returns a 'value'. I want to add both the value and updated s to a dictionary. I get the above error.

like image 430
user220201 Avatar asked Aug 30 '15 23:08

user220201


2 Answers

{[1, 2, 3]: 1}

TypeError: unhashable type: 'list'

A dict key has to be a immutable type.

List or bytearray can't be use as a key because they are mutable and for this reason can't be unique since they can be changed.


It seems that if an object as a __hash__ method it can be use as a key though :

I'm able to use a mutable object as a dictionary key in python. Is this not disallowed?

like image 76
Richard Avatar answered Oct 17 '22 21:10

Richard


Unhashable/immutable objects can't be used as keys because you may not find them after you've put them in the mapping :-)

x = [1, 2]
# suppose this works
mapping = {x: "this is x"}
# change x
x.append(3)

Thinking of how a mapping is actually implemented (buckets by hash), we (may) now have a key in the wrong bucket ([1, 2, 3] in [1, 2]'s bucket). We are never going to find it.

You can create a string, or use a tuple (both are immutable) and use them as keys.

like image 34
Reut Sharabani Avatar answered Oct 17 '22 20:10

Reut Sharabani