How to obtain a dictionary of the named arguments in a Python function
<p>I know it's a common case for people to give a function an arbitrary number of kwargs with <code>**kwargs</code>, and then access them as a dictionary; however, I want to explicitly specify my functions kwargs, but still be able to access them as a dictionary.</p>

<p>This is because I want my function to only receive specific <code>kwargs</code>, but I need to perform an identical operation with all of them, which I can put into a <code>for</code> loop.</p>

<pre><code>def my_func(kwarg1=None, kwarg2=None, kwarg3=None):
    kwargs = {} # After somehow getting all my kwargs into a dictionary

    for k in kwargs:
        # Do my operation
</code></pre>

<p>I do <strong>not</strong> want my function to receive an arbitrary number of <code>kwargs</code>, but I <strong>do</strong> want to access my <code>kwargs</code> in a dictionary.</p>

<p>This is Python3.3+ code that creates the list of keyword argument names automatically. Just for completness. I would prefer any of the simpler solutions.</p>

<pre><code>import inspect

def my_func(*, kwarg1=None, kwarg2=None, kwarg3=None):
    local_vars = locals()
    kwargs = {k: local_vars[k] for k in KWARGS_my_func}
    print(kwargs)

KWARGS_my_func = [p.name for p in inspect.signature(my_func).parameters.values()
                  if p.kind == inspect.Parameter.KEYWORD_ONLY]

my_func(kwarg2=2)
</code></pre>

python dictionary parameters