0

I want to pass a dictionary contains unknown numbers of key/pair to a function called save, and inside the function, all the key/pair from the dictionary will be unpacked into keyword arguments for a class.

How can I achieve something like this?

def save(my_dict):   
   my_model = MyMode(k1=v1, k2=v2, k3=v3...)
martineau
  • 119,623
  • 25
  • 170
  • 301
user1187968
  • 7,154
  • 16
  • 81
  • 152

2 Answers2

1

my_model = MyMode(**my_dict) is the solution.

user1187968
  • 7,154
  • 16
  • 81
  • 152
0

I tried passing a dictionary to a Button class init function for both simulation and tkinter. I noticed a difference: with simulation = True (my own Button class), I have to pass in as keyword arguments **dict, but with tkinter's Button class (simulation = False), I can pass in with or without **. Is there any explanation to that?

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)
Leon Chang
  • 669
  • 8
  • 12