+ 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

27th Jul 2020, 10:42 AM
Coder
Coder - avatar
9 Answers
27th Jul 2020, 11:07 AM
Oma Falk
Oma Falk - avatar
+ 10
A tuple can't contain a mutable object if it's used as a key ,all tuple elements should be immutable
27th Jul 2020, 10:58 AM
Abhay
Abhay - avatar
+ 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
27th Jul 2020, 2:17 PM
Ali Abdelhady
Ali Abdelhady - avatar
+ 4
Wow....the question becomes interesting
27th Jul 2020, 11:08 AM
Oma Falk
Oma Falk - avatar
+ 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])
29th Jul 2020, 4:39 AM
Tibor Santa
Tibor Santa - avatar
+ 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???
28th Jul 2020, 4:44 AM
Rick Shiffman
Rick Shiffman - avatar
+ 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
28th Jul 2020, 1:07 PM
HonFu
HonFu - avatar
+ 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)
29th Jul 2020, 5:18 AM
Rick Shiffman
Rick Shiffman - avatar
+ 2
It solved thanks Abhay
27th Jul 2020, 11:02 AM
Coder
Coder - avatar