Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a dictionary with inline function

Tags:

python

Do I have to formally define a function before I can use it as an element of a dictionary?

def my_func():
  print 'my_func'

d = {
  'function': my_func
}

I would rather define the function inline. I just tried to type out what I want to do, but the whitespace policies of python syntax make it very hard to define an inline func within a dict. Is there any way to do this?

like image 973
Matthew Taylor Avatar asked Jan 14 '12 17:01

Matthew Taylor


People also ask

How do you declare a dictionary?

To create a Dictionary, use {} curly brackets to construct the dictionary and [] square brackets to index it. Separate the key and value with colons : and with commas , between each pair. As with lists we can print out the dictionary by printing the reference to it.

Can we define function in dictionary Python?

Python defines a function by executing a def statement. Python defines your dict by executing your d = { etc etc etc} .

What is inline function in Python?

Python lambda functions, also known as anonymous functions, are inline functions that do not have a name. They are created with the lambda keyword. This is part of the functional paradigm built-in Python. Python lambda functions are restricted to a single expression.

Can we use append function in dictionary?

We can make use of the built-in function append() to add elements to the keys in the dictionary. To add element using append() to the dictionary, we have first to find the key to which we need to append to.


2 Answers

The answer seems to be that there is no way to declare a function inline a dictionary definition in python. Thanks to everyone who took the time to contribute.

like image 141
Matthew Taylor Avatar answered Oct 20 '22 11:10

Matthew Taylor


Do you really need a dictionary, or just getitem access?

If the latter, then use a class:

>>> class Dispatch(object):
...     def funcA(self, *args):
...         print('funcA%r' % (args,))
...     def funcB(self, *args):
...         print('funcB%r' % (args,))
...     def __getitem__(self, name):
...         return getattr(self, name)
... 
>>> d = Dispatch()
>>> 
>>> d['funcA'](1, 2, 3)
funcA(1, 2, 3)
like image 29
ekhumoro Avatar answered Oct 20 '22 10:10

ekhumoro