0

How to execute multiple value in python dictionary?

def func1():
    pass
def func2():
    pass
def func3():
    pass
def func4():


def main_menu():
    os.system('clear')
    print("\nWelcome, \n\n")
    print("1. First Question")
    print("2. Second Question")
    print("\n\n Type 'q' for Quit\n")
    choice = input(" >>  ").lower()
    if choice == '':
        main_menu()
    else:
        try:
            main_menus[choice]()
        except KeyError:
            print("Invalid selection, Please try again.\n")
            main_menu()
    return

main_menus = {
    '1' : func1, 
    '2' : func2, 
}

i want main_menus key have two value, like this for example

main_menus = {
    '1' : func1, func4
    '2' : func2, func3
}

so, if user input '1', it will execute func1 first, after finish, it will execute func4.. i can't call func4 from func1 like this:

def func1():
    return func4()

because func1, maybe will be use by another main_menus key, and will be pair with func3..

anyone have solution for this, if can, better not use for loop.

Thank you

Fixlensmith
  • 41
  • 1
  • 11

2 Answers2

0

Option 1 Using Eval

main_menus = {
    '1' : "func1(), func2()",
    '2' : "func2(), func3(),func4()"
}

try:
    eval(main_menus[choice])

Overall Code becomes:

import os

def func1():
  pass

def func2():
  pass

def func3():
  pass

def func4():
  pass

def main_menu():
  choice = ''
  while True:
    os.system('clear')
    print("\nWelcome, \n\n")
    print("1. First Question")
    print("2. Second Question")
    print("\n\n Type 'q' for Quit\n")

    choice = input(" >>  ").lower()
    if choice != 'q':
      try:
        eval(main_menus[choice])
      except KeyError:
          print("Invalid selection, Please try again.\n")
    else:
      break

  return


main_menus = {
    '1' : "func1(), func2()",
    '2' : "func2(), func3(),func4()"
}

main_menu()

Option 2 -- Use For Loop

Replace main_menus and try are in overall code above with:

main_menus = {
    '1' : [func1, func2],
    '2' : [func2, func3, func4]
}

try:
    for f in main_menus[choice]:
        f()
DarrylG
  • 16,732
  • 2
  • 17
  • 23
  • yes, i have try this before, it can..but maybe there is another way without for loop, because i have so many `keys` in that dictionary.. – Fixlensmith Dec 10 '19 at 04:23
  • @Fixlensmith--updated with the option of using eval, although I don't understand your issue with a for loop. Could you explain further? – DarrylG Dec 10 '19 at 04:45
  • i just want to know if there is another way, i just want to compare the speed between for loop and other option. – Fixlensmith Dec 10 '19 at 06:25
0

Just define a function that calls both of them.

def func12():
    func1()
    func2()
def func34():
    func3()
    func4()

main_menus = {
    '1': func12,
    '2': func34
}
Barmar
  • 741,623
  • 53
  • 500
  • 612