Skip to content Skip to sidebar Skip to footer

Boost Python 3 Iterate Over Dict

I used (Python 2.7) to iterate over a dict this way: boost::python::list myList = myDict.items(); for(int i = 0; i < len(myList); i++) { pytuple pair = extract

Solution 1:

Extending Ernest's comment the answer is casting the view to a list:

auto myList = list(myDict.items());

If is a proxy dictionary instead you need to do the following:

auto myList = list(call_method<object>(myProxyDict.ptr(), "items"));

Solution 2:

You can follow also this approach

boost::python::list keys = boost::python::list(global.keys());
for (int i = 0; i < len(keys); ++i) {
    boost::python::extract<std::string> extractor(keys[i]);
    if (extractor.check()) {
        std::string key = extractor();

        // access the dict via global[key] to the value
    }
}

Solution 3:

Another way:

object theIterable = theObjectDict.keys();
object theIterator = theIterable.attr("__iter__")();

do
{
        try
        {
            object theKey = theIterator.attr("__next__")();
            std::string memberkey = extract< std::string >( theKey );

        }
        catch(...)
        {
          PyObject*theError = PyErr_Occurred();
          if( theError )
          {
              PyObject *ptype, *pvalue, *ptraceback;
              PyErr_Fetch(&ptype, &pvalue, &ptraceback);
              if( ptype == PyExc_StopIteration )
              {
                    PyErr_Clear();
                    break;
              }
          }
          throw;
        }
} while(1);

Post a Comment for "Boost Python 3 Iterate Over Dict"