質問

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

役に立ちましたか?

解決

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 */
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top