I'd like to pass a dict to an object's constructor for use as kwargs.
Obviously:
foo = SomeClass(mydict)
Simply passes a single argument, rather than the dict's contents. Alas:
foo = SomeClass(kwargs=mydict)
Which seems more sensible doesn't work either. What am I missing?
Passing Dictionary as an argument In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.
With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.
Python Language Dictionary The dict() constructor The dict() constructor can be used to create dictionaries from keyword arguments, or from a single iterable of key-value pairs, or from a single dictionary and keyword arguments.
Python dict() Function The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.
Use :
foo = SomeClass(**mydict)
this will unpack the dict value and pass them to the function.
For example:
mydict = {'a': 1, 'b': 2}
SomeClass(**mydict) # Equivalent to : SomeClass(a=1, b=2)
To pass a dictionary to a constructor you have to do so by reference, which is by preceding it with **
, like so:
foo = SomeClass(**mydict)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With