Boost Python 3遍历字典

问题描述:

我使用(Python 2.7)通过以下方式遍历 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];
}

但是在升级到3.7后, items()不再返回列表,而是返回一个 view ,该视图只有在对其进行迭代之后才会实现.

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

如果我尝试从 items()初始化列表,则无法显示 TypeError:期望对象为list类型;取而代之的是dict_items类型的对象

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

如何使用Boost Python遍历Python 3+字典?

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

或者,如何将字典转换成列表?

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

扩展欧内斯特(Ernest)的评论,答案是将 view 强制转换为列表:

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