Friday, March 4, 2011

Passing a dictionary to a function in python as keyword parameters

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

Here is some pseudo-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?

From stackoverflow
  • Here ya go - works just any other iterable:

    d = {'param' : 'test'}
    
    def f(dictionary):
        for key in dictionary:
            print key
    
    f(d)
    
  • 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)
    
    Aaron Digulla : S.Lott: This is not possible.
    Javier : if you'd want this to help others, you should rephrase your question: the problem wasn't passing a dictionary, what you wanted was turning a dict into keyword parameters
    Matthew Trevor : It's worth noting that you can also unpack lists to positional arguments: f2(*[1,2])
    mipadi : "dereference": the usual term, in this Python context, is "unpack". :)
  • 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.

  • You could easily iterate through all items of a given dictionary like this;

    dictionary = {0: 'zero', 1: 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5: 'five'}
    
    for counter in range (0, len(dictionary)):
              dictionary[counter]
    

    Hope this helps.. XD

0 comments:

Post a Comment