【问题标题】:dictionary to keyword argument unpacking [duplicate]字典到关键字参数解包[重复]
【发布时间】:2017-11-26 11:13:37
【问题描述】:

我想将一个包含未知数量的键/对的字典传递给一个名为save 的函数,并且在函数内部,字典中的所有键/对将被解压缩到一个类的关键字参数中。

我怎样才能实现这样的目标?

def save(my_dict):   
   my_model = MyMode(k1=v1, k2=v2, k3=v3...)

【问题讨论】:

  • 你的意思是MyMode(**my_dict)
  • 查看odcumentation关于**字典解包。

标签: python arguments


【解决方案1】:

my_model = MyMode(**my_dict) 是解决方案。

【讨论】:

    【解决方案2】:

    我尝试将字典传递给模拟和 tkinter 的 Button 类 init 函数。我注意到一个区别:使用模拟 = True(我自己的 Button 类),我必须作为关键字参数传入 **dict,但是使用 tkinter 的 Button 类(模拟 = False),我可以带或不带 ** 传入。有什么解释吗?

    simulation = True
    dictA = dict(text="Print my name with button click", command=lambda: print("My name is here"), fg="blue")
    dictB = dict(text="Print your name with button click", command=lambda: print("Your name is there"),
                 fg="white", bg="black")
    if simulation == False:
        import tkinter as tk
        root = tk.Tk()
        dict = [dictA, dictB]
        for d in dict:
            # btn = tk.Button(root, d)  # This works too!?
            btn = tk.Button(root, **d)
            btn.pack()
        root.mainloop()
    else:
        class   Button:
            def __init__(self, **kwArgs):
                if (kwArgs.get('text') == None):
                    self.text = "button"
                else:
                    self.text = kwArgs['text']
    
                if (kwArgs.get('command') == None):
                    self.command = lambda arg: print(arg)
                else:
                    self.command = kwArgs['command']
    
                if (kwArgs.get('fg') == None):
                    self.fg = "black"
                else:
                    self.fg = kwArgs['fg']
    
                if (kwArgs.get('bg') == None):
                    self.bg = "white"
                else:
                    self.bg = kwArgs['bg']
    
                print("text = {0}, command inline function = {1}, fg color = {2}, bg color = {3}".
                    format(self.text, self.command, self.fg, self.bg))
    
        btnDefault = Button()
        btnDictA = Button(**dictA)
        btnDictB = Button(**dictB)
    

    【讨论】:

      猜你喜欢
      • 2011-03-09
      • 2020-10-22
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多