Login or Sign up

Dynamic arguments using dictionaries for Python functions

Posted by: littlemog on Nov. 30, 2009

I wrote one of those functions early in my Python learning career that looks like this,

    def update_user(first_name,last_name,email_add,title1='N',title2='N'):
            # Code to do something here

It gets messy once I have to pass the arguments in... which ended up with me calling the function like:

    update_user(fname,lname,email,title1,title2,title3,title4....)

But what if I only wanted to flag one of the 'titles' field and let the rest default to 'N'? Maybe:

    update_user(fname,lname,email,title4='Y')

That worked until I needed to construct the arguments on the fly, maybe because I'm calling the function after getting input from the user or on the command line. I found a simple solution using dictionaries. Say I needed to grab the title from the command line and now it rest in a variable call flag_title:

    dictodork = {flag_title: 'Y'}    # e.g. flag_title = 'title4'
    update_user(fname,lname,email,**dictodork)

That dictionary gets broken up into title4='Y' :)

Comments on This Post:

Please Login (or Sign Up) to leave a comment