Reputation: 3228
I have the function:
def do_something(arguments_list):
user = User(name = argument_list['name'],
age = argument_list['age'],
...
sex = argument_list['sex'])
The argument_list
(dictionary) don't always have the same keys. For example, sometimes it looks like this:
arguments_list = {'name': 'Zara', 'age': 7, 'sex': 'Male'}
but it also could be:
arguments_list = {'name': 'Zara'}
How can I dynamically pass arguments to the function (in this case constructor of User class) depends on what keys are in the dictionary?
Upvotes: 0
Views: 131
Reputation: 2054
This would take any number of keyword arguments and pass them to User
:
def do_something(**kwargs):
user = User(**kwargs)
If you know more about the arguments you could also do something like this (in this case you most likely want the do_something
default values to be the same as the User
default values):
def do_something(name=None, age=None, sex=None):
user = User(name=name, age=age, sex=sex)
Let me know if something needs clarification.
Here you have more information about *args
and **kwargs
:
https://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
Upvotes: 3
Reputation: 1406
>>> def do_something(**arguments_list):
name = arguments_list['name']
>>> do_something(name="name")
Upvotes: -2