How to use dictionary instead of if statement in python?

橙三吉。 提交于 2019-12-24 08:44:26

问题


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()

回答1:


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()


来源:https://stackoverflow.com/questions/49881114/how-to-use-dictionary-instead-of-if-statement-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!