2

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])
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Related: [TypeError: unhashable type: 'set'](https://stackoverflow.com/q/53143163/4518341), [Add list to set?](https://stackoverflow.com/q/1306631/4518341) – wjandrea Jan 27 '20 at 15:28

2 Answers2

5

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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

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}