[Tutor] Dictionaries supplying arguments to functions

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 6 Aug 2001 19:48:29 -0700 (PDT)


On Tue, 7 Aug 2001, Tom Nott wrote:

> Is it possible to have a dictionary supply the arguments to a function?
> 
> I'm after something like:
> 
> def fn(p1, p2, p3):
>     print p1
>     print p2
>     print p3
> 
> d = {'p1':'How ', 'p2':'are ', 'p3':'you'}
> 
> callWithDict(fn, d)


Yes, very much so:

###
>>> def fn(p1, p2, p3):
...     print p1
...     print p2
...     print p3
...
>>> d = { 'p1' : 'Pie 1',
...       'p2' : 'Pentium 2',
...       'p3' : 'Phosphorus 3' }
>>> fn(**d)
Pie 1
Pentium 2
Phosphorus 3
###


Put two stars at the front of the dictionary you're feeding in the
function, and it'll match up properly with the arguments.  The reason they
use double stars is because '**' is also used to get keyword arguments as
a dictionary:


###
>>> def getInsertQuery(table, **key_values):
...     query = "insert into " + table
...     mykeys = key_values.keys()
...     query += " (%s) " % ', '.join(mykeys)
...     values = [ key_values[key] for key in mykeys ]
...     query += " values (%s) " % ', '.join(values)
...     return query
...
>>> getInsertQuery('messages', subject='testing',
...                            message='this is a test',
...                            author='dyoo')
'insert into messages (subject, author, message)  values (testing, dyoo,
this is a test) '
###


You might find out more about this here:

http://python.org/doc/current/tut/node6.html#SECTION006720000000000000000

although, admittedly, I'm a little forgetful about where I actually
learned about this feature... *grin* Does anyone know where this is
actually documented?

Hope this helps!