Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set as dictionary key

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])
like image 272
Temitope Oladokun Avatar asked Aug 22 '26 00:08

Temitope Oladokun


1 Answers

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
like image 156
Jean-François Fabre Avatar answered Aug 23 '26 13:08

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!