简体   繁体   English

从参数中选择所有非None元素并将它们放在python字典中的优雅方法是什么?

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

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? 有人可以建议一个更优雅,pythonic的方法来完成非空命名变量并将它们放在字典中吗? 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; “varone”的值必须进入var1,“vartwo”必须进入var2,依此类推; Thanks. 谢谢。

You could use kwargs : 你可以使用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. 使用这种语法,Python不需要显式指定任何参数列表,并允许函数处理他们想要的任何旧关键字参数。

If you're specifically looking for keys var1 etc instead of varone you just modify the function call: 如果您专门寻找密钥var1等而不是varone您只需修改函数调用:

>>> 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. 同样,您必须更改参数名称以与输出键保持一致。

Use **kwargs . 使用**kwargs Example: 例:

def function(**kwargs):
    if not kwargs:
        raise Exception("No values provided")
    for k, v in kwargs.items():
        print("%s: %r") % (k, v)

If you really are going to call function with None arguments, you can strip them out: 如果你真的打算使用None参数调用function ,你可以将它们删除:

def function(**kwargs):
    for k, v in kwargs.items():
        if v is None:
            del kwargs[k]
    if not kwargs:
        raise Exception("No values provided")
    for k, v in kwargs.items():
        print("%s: %r") % (k, v)

Obviously you could call the dict values instead, but kwargs is the conventional name, and will make your code more intelligible to other people. 显然你可以调用dict values ,但kwargs是常规名称,并且会使你的代码对其他人更容易理解。

Well, you can pass all those values inside a keyword argument : - 好吧,你可以在keyword argument传递所有这些值: -

def function(*nkwargs, **kwargs):
    values = {}

    for k in kwargs:
        if kwargs[k] is not None:
            values[k] = kwargs[k]
    if not values:
        raise Exception("No values")
    print values

try:
    function()
except Exception, e:
    print e

function(varOne=123, varTwo=None)
function(varOne=123, varTwo=234)

OUTPUT : - 输出 : -

No values
{'varOne': 123}
{'varOne': 123, 'varTwo': 234}

Call your function as usual, but accept as **kwargs . 像往常一样调用你的函数,但接受**kwargs Then filter them: 然后过滤它们:

def fn(**kwargs):
    items = {'var%s' % i: v for i, (k, v) in enumerate(items)}

fn(a=1, b=2, c=3)

if you need a specific set of names, then make a dict of names: 如果你需要一组特定的名字,那就制作一个名字的词典:

    names = dict(zip('varOne varTwo varThree'.split(), range(1, 4)))

walk over this dict and check if the var is in kwargs: 走过这个字典并检查var是否在kwargs中:

items = {'var%s' % k: kwargs[v] for k, v in names.items() if v in kwargs}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Python的子列表中获取所有非项目的索引? - Getting the indices of all non-None items from a sub-list in Python? 用另一个字典更新一个字典,但只有非 None 值 - Update a dictionary with another dictionary, but only non-None values 使用 And 运算符为每个非 None 参数添加不同的 Function - Adding Different Function for Every non-None Parameters with And Operator 在Python的序列中从谓词查找第一个非返回值 - Find first non-None returned value from predicate over a sequence in Python 将元素从文本文件附加到字典并将它们设置为无 [Python] - Appending Elements to a Dictionary from a text file and Setting them to None [Python] 尝试使用 python 从 azure 函数触发 url,错误提示“没有 $return 绑定返回非无值” - Trying to trigger an url from azure functions using python, errored saying “without a $return binding returned a non-None value” 获取列表中最近的非无项目 - Get Nearest non-None Item in List 如果元素不是无,则在列表中添加元素的优雅方式 - Elegant way to add elements in a list if the elements are not None Python:一种从 Python 字典中删除空列表的优雅方法 - Python: An elegant way to delete empty lists from Python dictionary 什么是处理python中不存在的属性的最优雅方法? - What is the most elegant way to handle non-existing attribute in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM