Steve Sawyer
Steve Sawyer

Reputation: 1885

Python function argument list from a dictionary

I'm still relatively new to Python, and sometimes something that should be relatively simple escapes me.

I'm storing the results of a POST operation to a database table as a character string formatted as a dictionary definition. I'm then taking that value and using eval() to convert it to an actual dict object, which is working great as it preserves the data types (dates, datetimes, integers, floats, strings etc.) of the dictionary data elements.

What has me flummoxed is using the resulting dictionary to construct a set of keyword arguments that can then be passed to a function or method. So far, I haven't been able to make this work, let alone figure out what the best/most Pythonic way to approach this. The dictionary makes it easy to iterate over the dictionary elements and identify key/value pairs but I'm stuck at that point not knowing how to use these pairs as a set of keyword arguments in the function or method call.

Thanks!

Upvotes: 1

Views: 249

Answers (3)

Steve Sawyer
Steve Sawyer

Reputation: 1885

@tzaman and @Alex_Thornton - thanks - your answers led me to the solution, but your answers weren't clear re the use of the **kwargs in the function call, not the function definition. It took me a while to figure that out. I had only seen **kwargs used in the function/method definition before, so this usage was new to me. The link that @tzaman included triggered the "aha" moment.

Here is the code that implements the solution:

def do_it(model=None, mfg_date=None, mileage=0):
    # Proceed with whatever you need to do with the 
    # arguments
    print('Model: {} Mfg date: {} Mileage: {}'.format(model, mfg_date, mileage)

dict_string = ("{'model':'Mustang,"
               "'mfg_date':datetime.datetime.date(2012, 11, 24),"
               "'mileage':23824}")

dict_arg = eval(dict_string)

do_it(**dict_arg)  # <---Here is where the **kwargs goes - IN THE CALL

Upvotes: 0

anon582847382
anon582847382

Reputation: 20351

You are looking for **kwargs. It unpacks a dictionary into keyword arguments, just like you want. In the function call, just use this:

some_func(**my_dict)

Where my_dict is the dictionary you mentioned.

Upvotes: 1

tzaman
tzaman

Reputation: 47780

I think you're just looking for func(**the_dict)?

Understanding kwargs in Python

Upvotes: 4

Related Questions