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>Assuming you have no positional arguments, you could get access to your kwargs via <code>locals</code> if you put it at the top of your function:</p>

<pre><code>def my_func(kwarg1=None, kwarg2=None, kwarg3=None):
    # Don't add any more variables before the next line!
    kwargs = dict(locals())

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

<p>This is hacky (at best) and it's probably better to just spell it out:</p>

<pre><code>kwargs = {'kwarg1': kwarg1, ...}
</code></pre>

python dictionary parameters