Search code examples
pythonc++dictionaryboost

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<pytuple>(itemsView[t]);
     string memberKey = extract<string>(pair[0]);
     object member = pair[1];
}

But after upgrading to 3.7 items() no longer returns a list but a view, which materializes only after iterating over it.

If I try to initialize a list from items() it fails saying TypeError: Expecting an object of type list; got an object of type dict_items instead

How can I iterate over a Python 3+ dict using Boost Python?

Or, How could I convert the dictionary into a list?


Solution

  • 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"));