99lives 99lives - 2 months ago 7
Python Question

How to obtain a dictionary of the named arguments in a Python function

I know it's a common case for people to give a function an arbitrary number of kwargs with

**kwargs
, and then access them as a dictionary; however, I want explicitly specify my functions kwargs, but still be able to access them as a dictionary.

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

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


I do not want my function to receive an arbitrary number of kwargs, but I do want to access my kwargs in a dictionary.

Answer

Simply create a dictionary as normal, retrieving the values of each argument.

def my_func(kwarg1=None, kwarg2=None, kwarg3=None):
    kwargs = {'kwarg1':kwarg1, 'kwarg2':kwarg2, 'kwarg3':kwarg3}

    for k in kwargs:
        # Do my operation