Give function defaults arguments from a dictionary in Python

后端 未结 8 2304
予麋鹿
予麋鹿 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:46

    try this:

    # Store the default values in a dictionary
    >>> defaults = {
    ...     'a': 1,
    ...     'b': 2,
    ... }
    >>> def f(x, **kwa):
            # Each time the function is called, merge the default values and the provided arguments
            # For python >= 3.5:
            args = {**defaults, **kwa}
            # For python < 3.5:
            # Each time the function is called, copy the default values
            args = defaults.copy()
            # Merge the provided arguments into the copied default values
            args.update(kwa)
    ...     print(args)
    ... 
    >>> f(1, f=2)
    {'a': 1, 'b': 2, 'f': 2}
    >>> f(1, f=2, b=8)
    {'a': 1, 'b': 8, 'f': 2}
    >>> f(5, a=3)
    {'a': 3, 'b': 2}
    

    Thanks Olvin Roght for pointing out how to nicely merge dictionaries in python >= 3.5

提交回复
热议问题