Home > other >  Python - execute only one value from dictionary
Python - execute only one value from dictionary

Time:08-26

I'm trying to understand something. I have code something like this

all_commands = {
    'cpu': print('so much cpu'),
    'user': print('so much users')
}

if args[0] in all_show.keys():
    return all_show[args[0]]

I want to execute only i.e. second key - 'user' but in every way I know it is executing both of them. Main goal is to avoid ifology, elif isn't solution. I can't use match case from 3.1 because it should be done in 3.4 version (for compatibility with older Unix systems) Is there any better solution to do this? I've searched SO without success.

CodePudding user response:

You're calling print() when you create the dictionary, not when the values are accessed.

You should put functions in the dictionary, then call them when you access it. You can use lambda to turn a simple one-liner into a function.

all_commands = {
    'cpu': lambda: print('so much cpu'),
    'user': lambda: print('so much users')
}

if args[0] in all_commands:
    return all_commands[args[0]]()

DEMO

CodePudding user response:

You're not storing a function in each key when you create your dictionary, instead you're actually calling print on every key. Instead create functions using lambda that you can call later.

all_commands = {
    'cpu': lambda: print('so much cpu'),
    'user': lambda: print('so much users')
}

Here's how you would call the function for 'cpu':

all_commands['cpu']()  # prints 'so much cpu'

CodePudding user response:

You could use lambdas for all_commands:

all_commands = {
    'cpu': lambda: print('so much cpu'),
    'user': lambda: print('so much users')
}

if args[0] in all_commands:
    all_commands[args[0]]()
  • Related