[python-win32] Re: Parsing a Python dictionary inside a Python extension
Roger Upole
rwupole at msn.com
Sat May 28 08:53:36 CEST 2005
<quadric at primenet.com> wrote:
> Hi,
>
> I would like to pass a dictionary from my Python code to my Python
> extension, extract
> various values from the dictionary (from within the extension) , modify
> the
> values for the
> relevant keys and return the modified dictionary to Python.
>
> Can someone point me to an example of what the C code might look like to
> do
> this?
>
>
> I tried something like this and it has not worked.
>
>
> static PyObject * ModifyDictionary( PyObject * self , PyObject * args )
> {
> int atab1 = 0 , atab2 = 0;
> PyObject * vdict = NULL;
> PyObject * item = NULL;
> PyObject * ndict = NULL;
>
> PyArg_ParseTuple( args , "O" , & vdict );
You really should be checking if this call succeeded.
>
> if ( (item = PyDict_GetItemString( vdict , "atab1")) != NULL
You should verify that the object is actually a dictionary, see
PyDict_Check.
> ) PyArg_ParseTuple( item , "i" , &atab1 );
PyArg_ParseTuple only parses tuples. You can use one
one of the conversion functions (eg PyInt_AsLong) to
convert this.
> if ( (item = PyDict_GetItemString( vdict , "atab2")) != NULL
> ) PyArg_ParseTuple( item , "i" , &atab2 );
>
> // modify values here and rebuild the dictionary
> // ndict = Py_BuildValue( ........create dictionary here ..........)
>
> return ndict ;
> }
>
>
> Can someone tell me where I am going wrong or point me to an example?
>
> Thanks for your help.
>
You can also use (mis)use PyArg_ParseTupleAndKeywords to extract items en
masse
from a dict, see PyACL.cpp for an example:
http://cvs.sourceforge.net/viewcvs.py/*checkout*/pywin32/pywin32/win32/src/PyACL.cpp
Roger
More information about the Python-win32
mailing list