Totte Karlsson
Totte Karlsson

Reputation: 1341

How to convert a returned Python dictionary to a C++ std::map<string, string>

I'm calling Python from C++, and trying to perform some data conversions.

For example, if I call the following Python function

def getAMap():
   data = {}
   data["AnItem 1"] = "Item value 1"
   data["AnItem 2"] = "Item value 2"
   return data

from C++ as:

PyObject *pValue= PyObject_CallObject(pFunc, NULL);

where pFunc is a PyObject* that points to the getAMap python function. Code for setting up pFunc omitted for clarity.

The returned pointer, pValue is a pointer to a (among other things) Python dictionary. Question is, how to get thh dictionary into a std::map on the C++ side as smoothly as possible?

I'm using C++ Builder bcc32 compiler that can't handle any fancy template code, like boost python, or C++11 syntax.

(Changed question as the python object is a dictionary, not a tuple)

Upvotes: 3

Views: 3171

Answers (1)

Major
Major

Reputation: 562

It's pretty ugly, but I came up with this:

std::map<std::string, std::string> my_map;

// Python Dictionary object
PyObject *pDict = PyObject_CallObject(pFunc, NULL);

// Both are Python List objects
PyObject *pKeys = PyDict_Keys(pDict);
PyObject *pValues = PyDict_Values(pDict);

for (Py_ssize_t i = 0; i < PyDict_Size(pDict); ++i) {
    // PyString_AsString returns a char*
    my_map.insert( std::pair<std::string, std::string>(
            *PyString_AsString( PyList_GetItem(pKeys,   i) ),
            *PyString_AsString( PyList_GetItem(pValues, i) ) );
}

Upvotes: 1

Related Questions