Search code examples
pythonfunctiondictionaryparameter-passingnamed

Is there a way to convert named function arguments to dict


I am trying to find out if there is a way to convert named arguments to dict.

I understand using **kwargs in place of individual named arguments would be pretty straight forward.

def func(arg1=None, arg2=None, arg3=None):
    # How can I convert these arguments to {'arg1': None, 'arg2': None, 'arg3': None}`

Solution

  • You can use locals() to get the local arguments:

    def func(arg1=None, arg2=None, arg3=None):
        print(locals())
    
    func()  # {'arg3': None, 'arg2': None, 'arg1': None}