问题
I ran the below line of code in Python but got an error titled "TypeError: unhashable type: 'set' ". I want to turn that key to a list. How can I solve this error?
dictionary = {
'a' : [[1,2,3],[4,5,6],[7,8,9]],
'b' : 2,
{100} : 3
}
print(dictionary['a'][1][2])
回答1:
keys of a dictionary must be hashable (or better: immutable). set
objects are mutable (like lists)
you could use a frozenset
instead
dictionary = {
'a' : [[1,2,3],[4,5,6],[7,8,9]],
'b' : 2,
frozenset({100}) : 3
}
A frozenset is a set
that is immutable. It's a builtin type. Now you can get the value even by passing a frozenset made of lists/tuples with duplicate entries/any order in the list and it still finds the value
>>> dictionary[frozenset((100,100))]
3
回答2:
You can not have set
as a dict key. Keys must be hashable objects (you may interpret it as immutable). So you can use tuple
instead:
dictionary = {'a': [[1,2,3],[4,5,6],[7,8,9]], 'b': 2, (100,): 3}
来源:https://stackoverflow.com/questions/59933892/set-as-dictionary-key