Search code examples
pythonc++python-2.7boost

How iterate (key, value) boost::python:dict


How can I iterate in C++ over my boost::python:dict ? I need key and value in every loop round.

My try was this:

for (auto x : MyBoostPythonDict.iteritems())
{
    // determine key
    // determine value 
    // ...
}

I got this error: C3312 no callable 'end' function found for type 'boost::python::api::object'


Solution

  • You can simply loop over all key/value pairs as follows:

    using namespace boost::python;
    
    list items = MyBoostPythonDict.items();
    for(ssize_t i = 0; i < len(items); ++i) {
        object key = items[i][0];
        object value = items[i][1];
        // ...
    }
    

    Now you need to extract the corresponding types from key and value. Assuming both are of type int you would use:

    extract<int> key_int(key);
    extract<int> value_int(value);
    
    if (key_int.check() && value_int.check()) {
        cout << key_int << ": " << value_int << endl;
    }