Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing dict to constructor?

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?

like image 929
mikemaccana Avatar asked Mar 18 '11 16:03

mikemaccana


People also ask

Can you pass a dictionary to a class in Python?

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.

Should I use dict () or {}?

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.

What is a dict constructor?

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.

What does dict () do in Python?

Python dict() Function The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.


2 Answers

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)
like image 178
mouad Avatar answered Sep 27 '22 19:09

mouad


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)
like image 26
jathanism Avatar answered Sep 27 '22 18:09

jathanism