字典到关键字参数解包

时间:2017-06-23 01:49:43

标签: python arguments

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

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我尝试将字典传递给Button类 init 函数,以进行模拟和tkinter。我注意到了一个区别:使用Simulation = True(我自己的Button类),我必须作为关键字参数** dict传入,但是使用tkinter的Button类(simulation = 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)