Search code examples
pythondictionaryif-statementswitch-statementpyqt4

How to use dictionary instead of if statement in python?


I have a function that pops-up a message box after you click on a button using PyQt4 in python. I use 'sender()' to determine which button was clicked and then set the text of pop-up window accordingly. This function works perfectly with 'if statements'. However I was wondering how do I write a function with same functionality using a dictionary (since there is no switch statement in python and there are too many if statements in my code)?

def pop_up(self):
    msg = QtGui.QMessageBox()
    msg.setIcon(QtGui.QMessageBox.Information)
    sender = self.MainWindow.sender()

    if sender is self.button1:
        msg.setText("show message 1")
    elif sender is self.button2:
        msg.setText("show message 2")
    elif sender is self.button3:
        msg.setText("show message 3")
    elif sender is self.button4:
        msg.setText("show message 4")
    elif sender is self.button5:
        msg.setText("show message 5")
    elif sender is self.button6:
        msg.setText("show message 6")
    .
    .
    .
    .
    .
    elif sender is self.button36:
        msg.setText("show message 36")


    msg.exec()

Solution

  • Your dictionary would looks something like

    button_dict = {
        self.button1: "Message 1",
        self.button2: "Message 2",
        self.button36: "Message 36",
    }
    

    Then you can access the values like you would any dictionary

    def pop_up(self):
        msg = QtGui.QMessageBox()
        msg.setIcon(QtGui.QMessageBox.Information)
        sender = self.MainWindow.sender()
        message_text = button_dict[sender]
        msg.setText(message_text)
        msg.exec()