【问题标题】:How to send a dictionary to a function that accepts **kwargs?如何将字典发送到接受 **kwargs 的函数?
【发布时间】:2010-12-06 06:56:02
【问题描述】:

我有一个接受通配符关键字参数的函数:

def func(**kargs):
    doA
    doB

如何向它发送字典?

【问题讨论】:

标签: python


【解决方案1】:

func(**mydict)

这意味着函数内部的 kwargs=mydict

mydict 的所有键都必须是字符串

【讨论】:

    【解决方案2】:

    只需使用func(**some_dict) 调用它。

    这记录在section 4.7.4 of python tutorial

    注意 same dictnot 传递到函数中的。创建了一个新副本,所以some_dict is not kwargs

    【讨论】:

    • “创建了一个新副本” - 我在哪里可以找到这种行为的官方文档?
    【解决方案3】:

    您的问题不是 100% 清楚,但如果您想通过 kwargs 传递 dict,您只需将该 dict 作为另一个 dict 的一部分,如下所示:

    my_dict = {}                       #the dict you want to pass to func
    kwargs  = {'my_dict': my_dict }    #the keyword argument container
    func(**kwargs)                     #calling the function
    

    那么你就可以在函数中捕捉到my_dict

    def func(**kwargs):
        my_dict = kwargs.get('my_dict')
    

    或者...

    def func(my_dict, **kwargs):
        #reference my_dict directly from here
        my_dict['new_key'] = 1234
    

    当我将相同的一组选项传递给不同的函数时,我经常使用后者,但有些函数只使用一些选项(我希望这是有道理的......)。 但是当然有一百万种方法可以解决这个问题。如果您详细说明您的问题,我们很可能会为您提供更好的帮助。

    【讨论】:

      【解决方案4】:

      对于 python 3.6,只需将 ** 放在字典名称之前

      def lol(**kwargs):
          for i in kwargs:
              print(i)
      
      my_dict = {
          "s": 1,
          "a": 2,
          "l": 3
      }
      
      lol(**my_dict)
      

      【讨论】:

        【解决方案5】:

        使用装饰器通过变量、args 和 kwargs 传递参数的简单方法

        def printall(func):
            def inner(z,*args, **kwargs):
                print ('Arguments for args: {}'.format(args))
                print ('Arguments for kwargs: {}'.format(kwargs))
                return func(*args, **kwargs)
            return inner
        
        @printall #<-- you can mark Decorator,it will become to send some variable data to function  
        def random_func(z,*y,**x):
            print(y)
            print(x)
            return z
        
        z=1    
        y=(1,2,3)
        x={'a':2,'b':2,'c':2}
        
        a = random_func(z,*y,**x)
        

        【讨论】:

          猜你喜欢
          • 2023-03-05
          • 1970-01-01
          • 1970-01-01
          • 2015-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-05
          • 1970-01-01
          相关资源
          最近更新 更多