What is an elegant way to select all non-None elements from parameters and place them in a python dictionary?

python

Solution

You could use `kwargs`:

def function(*args, **kwargs):
    values = {}
    for k in kwargs:
        if kwargs[k] is not None:
            values[k] = kwargs[k]
    if not values:
        raise Exception("No values provided")
    return values

>>> function(varone=None, vartwo="fish", varthree=None)
{'vartwo': 'fish'}

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 `var1` etc instead of `varone` you just modify the function call:

>>> function(var1=None, var2="fish", var3=None)
{'var2': 'fish'}

If you want to be REALLY slick, you can use list comprehensions:

def function(**kwargs):
    values = dict([i for i in kwargs.iteritems() if i[1] != None])
    if not values:
        raise Exception("foo")
    return values

Again, you'll have to alter your parameter names to be consistent with your output keys.

Problem

``` 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.

Original source