Give function defaults arguments from a dictionary in Python

后端 未结 8 2337
予麋鹿
予麋鹿 2021-01-01 18:26

Let\'s imagine I have a dict :

d = {\'a\': 3, \'b\':4}

I want to create a function f that does the exact same thing than this function :

8条回答
  •  星月不相逢
    2021-01-01 18:48

    How about the **kwargs trick?

    def function(arg0, **kwargs):
        print("arg is", arg0, "a is", kwargs["a"], "b is", kwargs["b"])
    
    d = {"a":1, "b":2}
    function(0., **d)
    

    outcome:

    arg is 0.0 a is 1 b is 2
    

提交回复
热议问题