Problems with Dictionaries

0

I am trying to use a diccionario as a switch , My code is:

a = {'1': f1(x, y), '2':  f2(x)}
while True:
    try:
        selection = getOption()
        b = a[selection]

        break

    except Exception:
        print "Error"

But I have the following problem: If I select option 1, function f2 is executed, but this should not happen. How do I fix it?

    
asked by Alice 13.03.2016 в 18:47
source

2 answers

3

The key of the dictionaries must be a String , so if getOption() returns an integer, you must parse it to a String .

a = {'1': f1(x, y), '2':  f2(x)}
while True:
    try:
        selection = getOption()
        b = a[str(selection)]

        break

    except Exception:
        print "Error"
    
answered by 13.03.2016 в 19:35
2

At the time of the dictionary definition, you are invoking the functions f1 and f2 , and the values returned are those that are inserted in the dictionary.

If you want a switch , one way would be:

funcs = { '1': f1, '2':f2 }
while True:
    selection = getOption()
    f = funcs.get(selection, None)
    if not f is None:
      f(x,y)
    else:
      print "No existe la función"

Problems:

  • All functions have to use the same number of arguments, even if they do not use all the arguments
  • All functions return some value
  • Error control grows as the number of switch cases increases, so it is best done within each function.
  • Of course, each of these problems can be avoided, but my recommendation is that you use structures if..elif..else and avoid spreading errors to other parts if you can (eg: getOption should control their own errors)

    seleccion = getOption()
    if seleccion == 1:
        f1(x,y)
    elif seleccion == 2:
        f2(x)
    else:
        print "Selección errónea"
    
        
    answered by 14.03.2016 в 02:34