def function(varone=None, vartwo=None, varthree=None):
values = {}
if var1 is not None:
values['var1'] = varone
if var2 is not None:
values['var2'] = vartwo
if var3 is not None:
values['var3'] = varthree
if not values:
raise Exception("No values provided")
Can someone suggest a more elegant, pythonic way to accomplish taking placing non-null named variables and placing them in a dictionary? I do not want the values to be passed in as a dictionary. The key names of “values” are important and must be as they are. The value of “varone” must go into var1, “vartwo” must go into var2 and so on; Thanks.
You could use
kwargs:With this syntax, Python removes the need to explicitly specify any argument list, and allows functions to handle any old keyword arguments they want.
If you’re specifically looking for keys
var1etc instead ofvaroneyou just modify the function call:If you want to be REALLY slick, you can use list comprehensions:
Again, you’ll have to alter your parameter names to be consistent with your output keys.