简体   繁体   中英

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

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. I am asking is there a way to get the dict from the form of input like (a=1,b=2)

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

Please Use kwargs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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