How To Convert A Returned Python Dictionary To A C++ Std::map
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'] = 'It
Solution 1:
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) ) );
}
Post a Comment for "How To Convert A Returned Python Dictionary To A C++ Std::map"