Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 975
Jaigus Avatar asked Oct 27 '12 06:10

Jaigus


People also ask

How to Remove None elements from a list Python?

The Python filter() function is the most concise and readable way to perform this particular task. It checks for any None value in list and removes them and form a filtered list without the None values.

Can a dictionary value be none in Python?

None can be used as a dictionary key in Python because it is a hashable object. However, you should avoid using None as a dictionary key if you have to convert your dictionary to JSON as all keys in JSON objects must be strings.


1 Answers

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.

like image 191
atomicinf Avatar answered Oct 24 '22 09:10

atomicinf