2

I'm currently writing a Python module in C. In it, I have a dictionary that I iterate over like so:

PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(index, &pos, &key, &value))
    /* do interesting things here */

Later in the same method, I then want to loop over the dictionary again. However, PyDict_Next(...) continues to return NULL. Is there any way to reset the internal iteration counter used by PyDict_Next(...)?

Matt Patenaude
  • 4,497
  • 1
  • 22
  • 21

1 Answers1

4

The iterator is initialized by setting pos to 0. You can restart the iterator by setting pos to 0 again.

PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(index, &pos, &key, &value))
    /* do interesting things here */

pos = 0;

while (PyDict_Next(index, &pos, &key, &value))
    /* do even more interesting things here */
tdelaney
  • 73,364
  • 6
  • 83
  • 116