How to convert all arguments to dictionary in python [closed]

半世苍凉 提交于 2019-12-12 09:27:43

问题


I would like to my function func(*args, **kwargs) return one dictionary which contains all arguments I gave to it. For example:

func(arg1, arg2, arg3=value3, arg4=value4)

should return one dictionary like this:

{'arg1': value1, 'arg2': value2, 'arg3': value3, 'arg4': value4 }

回答1:


You can use locals() or vars():

def func(arg1, arg2, arg3=3, arg4=4):
    print(locals())

func(1, 2)

# {'arg3': 3, 'arg4': 4, 'arg1': 1, 'arg2': 2}

However if you only use *args you will not be able to differentiate them using locals():

def func(*args, **kwargs):
    print(locals())

func(1, 2, a=3, b=4)

# {'args': (1, 2), 'kwargs': {'a': 3, 'b': 4}}



回答2:


If you can't use locals like the other answers suggest:

def func(*args, **kwargs):
    all_args = {("arg" + str(idx + 1)): arg for idx,arg in enumerate(args)}
    all_args.update(kwargs)

This will create a dictionary with all arguments in it, with names.




回答3:


You are looking for locals()

def foo(arg1, arg2, arg3='foo', arg4=1):
    return locals()

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}

Output:

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}


来源:https://stackoverflow.com/questions/44412617/how-to-convert-all-arguments-to-dictionary-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!