Mobrine Hayde
Mobrine Hayde

Reputation: 365

Placing a function in dictionary

In Perl, if I want the value of a hash element to be a reference to an anonymous subroutine:

my $hash = { hi => sub { print "dummy" } };
$hash->{hi}->();   # Prints "dummy".

Is there an equivalent way for the previous hash/dict in Python?

Note: I need the key value to contain the function, not a reference to redirect to the function

Upvotes: 0

Views: 54

Answers (1)

Mark
Mark

Reputation: 92440

If I understand you correctly, you can use a lambda function to make an anonymous function:

d = {'key': lambda x: print(x)}
d['key']("hello")
# prints "hello"

If you need a more complex function, you are better off writing the function and adding a reference to the dictionary.

[per comment] The parameter isn't required for lambdas. You can also use:

d = {'key': lambda: print("Hello")}

and call it without the argument:

d['key']() # also prints "hello"

Upvotes: 2

Related Questions