Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Spread **kwargs into a dictionary similar to ES6 spread

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 # ???
    })

like image 960
jchi2241 Avatar asked Apr 27 '19 02:04

jchi2241


Video Answer


1 Answers

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})
like image 59
gmds Avatar answered Sep 30 '22 17:09

gmds