Paul Zet
Paul Zet

Reputation: 71

how to run only 1 function in a dictionary list?

I have a script in mind that would require an if statement with about 30+ elifs. So I'm trying a dictionary method:

def a():
    print('a')
    return 'A is the number'

def b():
    print('b')
    return 'vvb is the number'

def c():
    print('c')
    return 'c is the number'

name = input('type it in: ')

list = {'a': a(), 'b': b(), 'c': c()}

if name in list:
    this = list[name]
    print(this)
else:
    print('name not in list')

In theory when I input 'a', it should return "A is the number"

But this is what I get:

type it in: a
a
b
c
A is the number

So obviously the list executed all the functions, and if I had 30+ large functions, it would slow things down considerably. Is there a way to only execute the function that is being called?

Or maybe there's a better way to do this? Process finished with exit code 0

Upvotes: 1

Views: 49

Answers (2)

J_H
J_H

Reputation: 20495

list = {'a': a(), 'b': b(), 'c': c()}

Don't do that. What you wanted was this:

d = {'a': a, 'b': b, 'c': c}

Then, you'll want to call the function once you know what name is:

this = d[name]()

Also, please don't use identifiers like list or dir that are already defined as a builtin. Much better to call it d for dict. The list() function is very useful, and you may soon find you need to call it, perhaps even within the same function. Calling a thing a "list" when it is not a list will not help you to correctly reason about it.

Often an identifier along the lines of name_to_fn[] will be appropriate for a dict mapping, spelling out that in this case it maps from name to function.

Upvotes: 3

One option is remove the function calls from the list keys (also rename list to something other than a built-in python keyword, like mylist).

Then call the resulting function within the print() function:

mylist = {'a': a, 'b': b, 'c': c}

if name in mylist.keys():
    this = mylist[name]
    print(this())

result:

type it in: a
a
A is the number

Upvotes: 1

Related Questions