迭代时从字典中删除项目

时间:2018-06-02 01:43:11

标签: python python-3.x python-2.7 dictionary

在一个函数中(我没有写,我刚开始玩它),作者试图迭代一个字典并同时从中删除项目。它出自书" OpenCV for Secret Agents"作者:Joseph Howse,用Python2编写,我试图将其更新为Python3。

这里发布的功能(减去缩进的评论):

    def deserialize(self, path):
        file = open(path, 'rb')
        self._references = scipy.io.loadmat(file)
#       toDelete = []
        for key in self._references.keys():
            value = self._references[key]
            if not isinstance(value, numpy.ndarray):
                # This entry is serialization metadata so delete it.
                del self._references[key]
#               toDelete.append(self._references[key])
                continue
            # The serializer wraps the data in an extra array.
            # Unwrap the data.
            self._references[key] = value[0]

这会生成RuntimeError: dictionary changed size during iteration。要删除项目而不抛出错误,我考虑将每个项目添加到列表toDelete,然后根据其键从字典中删除每个项目,如缩进注释行。我无法看到更简单的方法。我错过了什么吗?

0 个答案:

没有答案