【问题标题】:How to get a string from a dictionary and use it as a named parameter in any function?如何从字典中获取字符串并将其用作任何函数中的命名参数?
【发布时间】:2018-10-03 09:51:11
【问题描述】:

我有一本python字典,

mapper = {'my_func': ['a', 'b', 'c', 'd']}

我想调用一个带有 a、b、c、d 和 e 参数的函数 -

functn(a, b, c, d, e=None)

参数 a、b、c、d 是我在调用函数时要使用的,而不是 e,这些参数名称是在该字典中定义的。

如何解析字典值并将它们用作函数中的命名参数,同时将一些值传递给它们中的每一个?

例如:

我可以通过这样做获得命名参数a -

mapper['my_func'][0]

但是如何在上述函数中将该值用作命名参数呢?

有什么帮助吗?

【问题讨论】:

    标签: python dictionary functional-programming named-parameters


    【解决方案1】:

    您可以通过几个步骤来做到这一点:

    mapper = {'my_func': [1, 2, 3, 4]}
    
    def functn(v, w, x, y, z):
        return v + w + x + y + z
    
    # create dictionary of arguments to values
    d = {**dict(zip(list('vwxy'), mapper['my_func'])), **{'z': 5}}
    
    # unpack dictionary for use in function
    res = functn(**d)  # 15
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      相关资源
      最近更新 更多