DeviC3
DeviC3

Reputation: 67

Python - execute only one value from dictionary

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.

Upvotes: 1

Views: 64

Answers (3)

Barmar
Barmar

Reputation: 781633

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

Upvotes: 5

Steven Rumbalski
Steven Rumbalski

Reputation: 45552

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'

Upvotes: 2

pigrammer
pigrammer

Reputation: 3509

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

Upvotes: 0

Related Questions