+ 9
TypeError: unhashable type: 'list'
bad_dict = { ([1, 2, 3]): "one two three" } print(bad_dict ([1, 2, 3])) #i tried to make it a tuple to get immutable but got type error #guys please tell me how to solve this error
9 Respuestas
+ 10
A tuple can't contain a mutable object if it's used as a key ,all tuple elements should be immutable
+ 10
A dictionary key must be hashable.
A hashable object has a hash value which never changes.
All strings and numerical values are hashable, sequences that are immutable are also hashable, but only if they contain hashable objects.
A list is not, it can be modified.
We can have a list inside a tuple, that tuple remains immutable but it won't be hashable.
https://code.sololearn.com/cL9nUvwMIc1t/?ref=app
+ 4
Wow....the question becomes interesting
+ 4
Rick Shiffman the *args in function signature is an unknown number of unnamed arguments, represented by a tuple. And you can even pass it lists, if you want.
def unpack(*args):
print(type(args))
for arg in args:
print(arg)
unpack("x", 42, [1, 0])
+ 3
Oma Fall, and Abhay. Glad you posted the question, and Abhay's anwser. I had never thought about puting a mutible structure in tuple before. That kind of defeets reson for using a tupple and it makes sense that dictionary not be happy with a tupple a mutible sub-element in it.
By the way is there reason or use for a tupple with mutible sub-elements in it???
+ 3
I want to point out that Ali gave the righter answer here.
It's not about the immutability.
You can create a class of your own and use (mutable) instances as keys for the dict.
https://www.sololearn.com/post/477553/?ref=app
+ 3
thanks Tibor Santa, I sould have thought about that, since I wrote my own version of printf() for python. I feel dumb now
def printf( format, *vals ): #I like printf
sys.stdout.write( format % vals)
+ 2
It solved thanks Abhay