0

I am trying to select one of the 16 dictionaries that I have created, based on the value of 4 input variables.

I think it could be done with switch but so far I have not been able to get it.

I think the "logic" could be something similar to this:

variable_1 = 0
variable_2 = 1
variable_3 = 1
variable_4 = 0



def func_select_dict(variable_1, variable_2, variable_3, variable_4)

        switch(0,0,0,0):
                final_dictionary = dictionary_1

        switch(0,0,0,1):
                final_dictionary = dictionary_2

        switch(0,0,1,0):
                final_dictionary = dictionary_3

        ...............

        switch(1,1,1,1):
                final_dictionary = dictionary_16

Any idea?

Inakima
  • 11
  • Python doesn't have a switch case statement, so you might need to rethink. – khelwood Sep 17 '20 at 17:32
  • Does this answer your question? [Why doesn't Python have switch-case?](https://stackoverflow.com/questions/46701063/why-doesnt-python-have-switch-case) – Sencer H. Sep 17 '20 at 18:22

1 Answers1

0

If you put your dictionaries in a list, for example

>>> dicts = [{'dict': i} for i in range(16)]
>>> dicts
[{'dict': 0}, {'dict': 1}, {'dict': 2}, {'dict': 3}, {'dict': 4}, {'dict': 5}, {'dict': 6}, {'dict': 7}, {'dict': 8}, {'dict': 9}, {'dict': 10}, {'dict': 11}, {'dict': 12}, {'dict': 13}, {'dict': 14}, {'dict': 15}]

You can use some clever bit-shifting to index into that list based on your variables

def to_index(v1, v2, v3, v4):
    return v1 << 3 | v2 << 2 | v3 << 1 | v4

For example

>>> to_index(0, 1, 1, 0)
6
>>> dicts[to_index(0, 1, 1, 0)]
{'dict': 6}

Your current approach will not work because Python does not have switch statements, and even if it did canonically that only works with integral types, not tuples.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218