Reputation: 25999
I'm new to python and experimenting a bit but having trouble making a list into a tuple to use as a dictionary key. Here's an example, which should make it more clear:
dict_of_lists_values = {}
dict_of_lists_values[('dog', 'cat')] = 10
dict_of_lists_values[('dog1', 'cat1')] = 10
dict_of_lists_values[('dog1', 'cat2')] = 10
dict_of_lists_values
{('dog', 'cat'): 10, ('dog1', 'cat2'): 10, ('dog1', 'cat1'): 10}
This works perfectly, and allows me to have a two values I can use as keys in a dictionary. When I try to apply this to a list, I get an error: TypeError: unhashable type: 'list'
dict_of_lists_values = {}
a = [22, 39, 0]
b = [15, 38, 12]
dict[(a, b)] = 'please work'
Based on my previous experiment, I think if I convert the list into a string it would work but I want it as it as a list not a string.
Is this possible?
Upvotes: 2
Views: 338
Reputation: 34655
No. It's not possible to use list
types for dictionary keys. However, you could extend list
, make it hashable, and then use that new type. (Though it's a bit cumbersome.)
class hlist(list):
def __hash__(self):
# Hash it somehow; here, I convert it to a hashable tuple ... and then hash it
return hash(tuple(self))
l1 = hlist([1,2,3])
l2 = hlist([4,5,6])
d = {
l1:"Hi.",
l2:"Hello!"
}
Please note Sven's comment below. Mutable keys are dangerous because their hash becomes stale if they are modified.
Upvotes: 3
Reputation: 5760
Dictionaries in Python can only have immutable/hashable keys.
Strings, numbers, and tuples are immutable, so they can be used as dictionary keys. Instances have a unique __hash__()
, so they can also be used. But lists are mutable, so they cannot be used as keys.
Upvotes: 1
Reputation: 89907
Call tuple()
on a list to create a tuple with the elements in the list.
Upvotes: 4