我有一个函数,除了预期和必需的参数外,还可以接收意外数量的其他参数。我想将其他参数与期望的参数一起传递到字典中。 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 # ???
})
答案 0 :(得分:6)
您只是在寻找**
运算符。通常,{**a, **b}
(其中a
和b
是dicts
)会使用来自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'}