Search code examples
python-c-api

Loop Over Python Dictionary (using C API) Twice?


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(...)?


Solution

  • 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 */