pythoncpythonpython-c-apipyobject

Python C API: Problems trying to build a dictionary


I'm trying to build a Python dictionary using the C API but it seems it's not possible (Py_BuildValue returns a NULL object) to use a PyObject* as value. I have a situation like the following:

#include <python3.5/Python.h>
...
PyObject *myList = PyList_New(1);
PyList_SetItem(myList, 0, Py_BuildValue("i", 1));
dict = Py_BuildValue("{siso}",
           "anInt", myInt,
           "aList", mylist);

I'm looking for a solution working with generic size of the list. I didn't find anything about this in the official documentation and also googling for hours. Can somebody help me? Thanks in advance


Solution

  • You're using the wrong format spec. Here is an example.

    So, in order to build a dictionary, you do it like so:

    int a_c_int; // 1
    PyObject *a_python_list; // [1]
    // ...
    Py_BuildValue("{s:i,s:O}",  # note the capital O ;)
              "abc", a_c_int, 
              "def", a_python_list);    
    

    returns the python dict

    {'abc': 1, 'def': [1]}