Search code examples
pythondictionary

Can I reference key name in dict value definition?


Is there a way to reference name of key at definition time of the value of the key? For example:

cmds = {"DO1": get_data(key), "DO2": get_data(key), ...}

If it is available each key will be substituted "DO1", "DO2", ...:

print(cmds)
{"DO1": get_data("DO1"), "DO2": get_data("DO2"), ...}

How do I achieve this idea? I want to save any function call to dictionary, even conditions.


Solution

  • #1 Define your dictionary by comprehension :

    keys = ['DO1', 'DO2', ...]
    cmds = {key: get_data(key) for key in keys}
    

    #2 Yes it exists. This is a cleaner way to populate your dictionary as the key name is redundant. You can modify (statically or dynamically) the keys list to change your dictionary.

    #3 Also to have the rest of your code a little bit cleaner, you may want to separate your code into different modules and/or objects.

    For example you can create a handler, which methods are the explicit name of your cmds ("cmd1", "cmd2...)

    #handler.py
    class commandHandler:
        def cmd1(self, pyqt_object, data_string):
            pyqt_object.cmd1_btn.setText(data_string)
        
        def cmd2(self, pyqt_object, data_string):
            pyqt_object.cmd2_drop.setCurrentIndex(int(data_string))
    
        def cmd3(self, pyqt_object, data_string):
            pass #and so on...
    

    Meanwhile, in your original file, you can use generically this handler with the getattr function :

    #your original file
    command_handler = commandHandler()
    cmds = ['cmd' + str(i) for i in range(1, N+1)] #N being the number of commands
    for cmd in cmds:
        if cmd in data:
            getattr(command_handler, cmd)(self, data[cmd])
    

    This way, you have a more generic and reusable code. To add a cmd feature you just have to add a method to your handler.