3

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

ggagliano
  • 1,004
  • 1
  • 11
  • 27

1 Answers1

6

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]}
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
  • I've tried that but it doesn't work. Did you tried your code? – ggagliano Aug 01 '18 at 13:51
  • I have not but it's literally copied from where I linked. Have you read this? `O (object) [PyObject *] Pass a Python object untouched (except for its reference count, which is incremented by one). If the object passed in is a NULL pointer, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, Py_BuildValue() will return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.` – FHTMitchell Aug 01 '18 at 14:03
  • It seems that you also didn't read well enough the documentation because the 'o' do not work but the 'O' yes! So, correct your answer and I'll mark it as solved ;) – ggagliano Aug 01 '18 at 15:46
  • Ah yes, my mistake. In my defence it can be hard to tell the difference `o` and `O` when reading. Sorry about that; I'll edit the post. – FHTMitchell Aug 01 '18 at 15:51
  • 1
    You can double check [here](https://docs.python.org/3.5/c-api/arg.html) that the 'O' is mentioned only as upper case – ggagliano Aug 01 '18 at 15:51