In a function (which I didn't write, I'm just starting to play with it), the author tries to iterate over a dictionary and delete items from it at the same time. It's from the book "OpenCV for Secret Agents" by Joseph Howse and it's written in Python2, and I'm trying to update it to Python3.
Here's the function as it's published (minus the outdented comments):
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]
This generates RuntimeError: dictionary changed size during iteration
. To delete the items without throwing up the error, I'm thinking of adding each item to a list toDelete
and then deleting each item from the dictionary based on its key, as in the outdented comment lines. I can't see an easier way to do it. Am I missing something?