Python-将** kwargs传播到类似于ES6传播的字典中

时间:2019-04-27 02:03:58

标签: python python-3.x

我有一个函数,除了预期和必需的参数外,还可以接收意外数量的其他参数。我想将其他参数与期望的参数一起传递到字典中。 Python中是否存在“散布”运算符或类似于JavaScript ES6散布运算符的类似方法?

JS版本

function track({ action, category, ...args }) {
  analytics.track(action, {
    category,
    ...args
  })
}

Python版本

def track(action, category, **kwargs):
    analytics.track(action, {
        'category': category,
        ...**kwargs # ???
    })

1 个答案:

答案 0 :(得分:6)

您只是在寻找**运算符。通常,{**a, **b}(其中abdicts)会使用来自dict和{的组合键值对创建a {1}},其中键重叠的情况下b优先。一个例子:

b

输出:

def f(category, **kwargs):
    return {'category': category, **kwargs}

print(f('this_category', this='this', that='that'))

因此,您可能需要这样的东西:

{'category': 'this_category', 'this': 'this', 'that': 'that'}