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.
{[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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With