views:

3646

answers:

4

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?

A: 

Here ya go - works just any other iterable:

d = {'param' : 'test'}

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

f(d)
Patrick Harrington
+17  A: 

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)
Dave Hillier
S.Lott: This is not possible.
Aaron Digulla
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
Javier
It's worth noting that you can also unpack lists to positional arguments: f2(*[1,2])
Matthew Trevor
"dereference": the usual term, in this Python context, is "unpack". :)
mipadi
+3  A: 

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.

llimllib
A: 

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