Skip to content
Advertisement

Error when transforming (and reversing) Tuple Tuple to dict

I am trying to transform following tuple tuple into a dict (and a reversed one of that):

EDIT_TUTORING_PLACES_CHOICES_TRANSLATOR = (
  (AT_STUDENT, ['1']),
  (AT_TUTOR, ['2']),
  (ONLINE, ['3']),
  (AT_STUDENT_AND_TUTOR, ['1', '2']),
  (AT_STUDENT_AND_ONLINE, ['1', '3']),
  (AT_TUTOR_AND_ONLINE, ['2', '3']),
  (ALL, ['1', '2', '3']),
  
)

This is the code I use:

dict = {v: k for k, v in list(EDIT_TUTORING_PLACES_CHOICES_TRANSLATOR)}

And I receive the following error:

TypeError: unhashable type: ‘list’

How should I do this? Thank you a lot!

Advertisement

Answer

you are right, lists cannot be used as keys in python dict because key has to be immutable. However, you can archive your goal by using tuples instead of lists (as tuples are immutable) To create your dict use

tutor_place_array_to_int_map = {tuple(v): k for k, v in list(EDIT_TUTORING_PLACES_CHOICES_TRANSLATOR)}

so that your key in dict is immutable tuple and then you will be able to use:

sth = tutor_place_array_to_int_map[("1", "2")]
sth = tutor_place_array_to_int_map.get(("1", "2"))
sth = tutor_place_array_to_int_map.get(tuple(["1", "2"]))

etc.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement