Pass dynamic keyword arguments to a function or method

Posted: September 14, 2011 in Python

I recently had the problem that I needed to pass a set of generated keyword arguments to a function in python. I took a lot of digging, but I’ve now started using it a lot.

Lets take a simple function that takes 5 keywork arguments (kwards):

def function_with_five_kwargs(first='1st', second='2nd', third='3rd',
fourth='4th', fifth='5th'):
    return '%s, %s, %s, %s, %s' % (first,       second, third, fourth, fifth)

If you run this without kwargs, your output is:

1st, 2nd, 3rd, 4th, 5th

If you now want to change all those args, use a dictionary:

my_dict = {'first': 'first',
               'second': 'second',
               'third': 'third',
               'fourth': 'fourth',
               'fifth': 'fifth'}

print function_with_five_kwargs(**my_dict)

Now your output will be:

first, second, third, fourth, fifth

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s