Passing a dictionary to a function as keyword parameters

I'd like to call a function in python using a dictionary.

Here is some code:

d = dict(param='test')

def f(param):
    print param

f(d)

This prints {'param': 'test'} but I'd like it to just print test.

I'd like it to work similarly for more parameters:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(d)

Is this possible?

Answers


Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)

In[1]: def myfunc(a=4, b=2):
In[2]:    print a, b

In[3]: mydict = {'a': 100, 'b': 200}

In[4]: myfunc(**mydict)
100 200

A few extra details that might be helpful to know (questions I had after reading this and went and tested):

  1. The function can have parameters that are not included in the dictionary
  2. You can not override a parameter that is already in the dictionary
  3. The dictionary can not have parameters that aren't in the function.

Examples:

Number 1: The function can have parameters that are not included in the dictionary

In[5]: mydict = {'a': 100}
In[6]: myfunc(**mydict)
100 2

Number 2: You can not override a parameter that is already in the dictionary

In[7]: mydict = {'a': 100, 'b': 200}
In[8]: myfunc(a=3, **mydict)

TypeError: myfunc() got multiple values for keyword argument 'a'

Number 3: The dictionary can not have parameters that aren't in the function.

In[9]:  mydict = {'a': 100, 'b': 200, 'c': 300}
In[10]: myfunc(**mydict)

TypeError: myfunc() got an unexpected keyword argument 'c'

In python, this is called "unpacking", and you can find a bit about it in the tutorial. The documentation of it sucks, I agree, especially because of how fantasically useful it is.


Here ya go - works just any other iterable:

d = {'param' : 'test'}

def f(dictionary):
    for key in dictionary:
        print key

f(d)

Need Your Help

Reusable real time display with jQuery

jquery data-binding real-time

I'm attempting to update some text fields based on the the data that is entered into an input field in real time using jQuery. I have gotten a rough example of this working, but it's not very reusa...

Regular expression in javascript?

c# asp.net javascript regex

I want to know how to write the regular expression in javascript. Please help me. Give a simple example with details. I mean the source code (i am using asp.net and c# language).