如何在python中将所有参数转换为字典 [英] How to convert all arguments to dictionary in python

查看:427
本文介绍了如何在python中将所有参数转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对函数func(*args, **kwargs)返回一个字典,其中包含我提供给它的所有参数.例如:

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 }

推荐答案

您可以使用locals()vars():

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

func(1, 2)

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

但是,如果仅使用*args,则将无法使用locals()进行区分:

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}}

这篇关于如何在python中将所有参数转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆