简体   繁体   English

在Python中将输入函数参数放入字典的最佳方法是什么?

[英]What's the best method to get the input function parameter into a dictionary in Python?

what I want is, for a function: 我想要的是一个功能:

def test(a = 1, b = 2):
    return {'a':a, 'b':b}

for example test(a=2,b=1) gives {'a':2,'b':1}. 例如,test(a = 2,b = 1)给出{'a':2,'b':1}。 I want to do this automatically (like packing all the parameter into a dictionay), because my function is under development and there will be a lot of more arguments added, so I don't want to add this everywhere, is there a clean way to do so? 我想自动执行此操作(比如将所有参数打包成dictionay),因为我的函数正在开发中并且会添加更多参数,所以我不想在任何地方添加它,是否有一种干净的方式这样做?

The function's form must be test(a=1,b=2), I can't change this into test(**kwarg), because it will be a huge change to the existing code. 函数的形式必须是test(a = 1,b = 2),我无法将其更改为test(** kwarg),因为它将对现有代码进行巨大更改。 I am asking is there a way to get the dict from the form of input like (a=1,b=2) 我问有没有办法从输入形式得到dict,如(a = 1,b = 2)

def test(a = 1, b= 2):
    x =  locals()
    print(x)
test(a=5, b=6)

Please Use kwargs 请使用kwargs

def test(**kwargs):
   return kwargs
print (test(a=1,b=2))  
#OUTPUT:{'b': 2, 'a': 1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM