I have a function that could receive an unexpected amount of additional arguments in addition to the expected and required arguments. I would like to pass the additional arguments into a dictionary along with the expected arguments. Is there a "spread" operator or similar method in Python similar to JavaScript's ES6 spread operator?
Version in JS
function track({ action, category, ...args }) {
analytics.track(action, {
category,
...args
})
}
Version in Python
def track(action, category, **kwargs):
analytics.track(action, {
'category': category,
...**kwargs # ???
})
You're just looking for the **
operator. In general, {**a, **b}
, where a
and b
are dicts
, creates a dict
with the combined key-value pairs from a
and b
, with b
taking precedence in case of key overlaps. An example:
def f(category, **kwargs):
return {'category': category, **kwargs}
print(f('this_category', this='this', that='that'))
Output:
{'category': 'this_category', 'this': 'this', 'that': 'that'}
In your case, therefore, you probably want something like this:
analytics.track(action, {'category': category, **kwargs})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With