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!
CodePudding user response:
The dict would have a list as a key, which is not possible. I solved the problem with nested if/else statements:
def tutor_place_array_to_int(arr: list[str]):
if arr.count('1') > 0:
if arr.count('2') > 0:
if arr.count('3') > 0:
return ALL
else:
return AT_STUDENT_AND_TUTOR
else:
if arr.count('3') > 0:
return AT_STUDENT_AND_ONLINE
else:
return AT_STUDENT
else:
if arr.count('2') > 0:
if arr.count('3') > 0:
return AT_TUTOR_AND_ONLINE
else:
return AT_TUTOR
else:
if arr.count('3') > 0:
return ONLINE
return None
ALL, AT_STUDENT_AND_TUTO, etc. are constants representing integers
CodePudding user response:
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.