-2

I'm using Python 3.5 and I want to know if its possible or if there's a way to use a list as a key in a dictionary in this way.

dict = {['a', 'c', 'b']: 1, 
    ['a', 'b', 'c']: 2, 
    ['b', 'a', 'c']: 5}

I need so hard to work with lists as keys...

Thank you!

I'l Follio
  • 573
  • 1
  • 7
  • 19

1 Answers1

2

You can't, a list is mutable and therefore non-hashable. Dictionary keys need to be hashable.

What you can do is use a tuple instead.

d= { ('a','b','c'): 1 }
Irmen de Jong
  • 2,739
  • 1
  • 14
  • 26
  • 2
    A list is not hashable because it doesn't implement a `__hash__` method. User-defined classes can be mutable but still hashable. All built-in container types that are mutable happen to be non-hashable. – juanpa.arrivillaga Feb 27 '17 at 23:19