This function is given a Python dictioanry and a list of string / unicode values. It will check whether all dictionary keys occur in this list and will return 1 (true) or 0 (false).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | //----------------------------------------------------------------------------
// Return set(dict.keys()).issubset(set([vkeys, ...])
// keys of dict must be string or unicode in Py2 and string in Py3!
// Parameters:
// dict - the Python dictionary object to be checked
// vkeys - a null-terminated list of keys (char *)
//----------------------------------------------------------------------------
int checkDictKeys(PyObject *dict, const char *vkeys, ...)
{
int i, j, rc;
PyObject *dkeys = PyDict_Keys(dict); // = dict.keys()
if (!dkeys) return 0; // no valid dictionary
j = PySequence_Size(dkeys); // len(dict.keys())
PyObject *validkeys = PyList_New(0); // make list of valid keys
va_list ap; // def var arg list
va_start(ap, vkeys); // start of args
while (vkeys != 0) // reached end yet?
{ // build list of valid keys to check against
#if PY_MAJOR_VERSION < 3
PyList_Append(validkeys, PyBytes_FromString(vkeys)); // Python 2
#else
PyList_Append(validkeys, PyUnicode_FromString(vkeys)); // python 3
#endif
vkeys = va_arg(ap, const char *); // get next char string
}
va_end(ap); // end the var args loop
rc = 1; // prepare for success
for (i = 0; i < j; i++)
{ // loop through dictionary keys
if (!PySequence_Contains(validkeys, PySequence_GetItem(dkeys, i)))
{
rc = 0;
break;
}
}
Py_DECREF(validkeys);
Py_DECREF(dkeys);
return rc;
}
|
The code represents the truth value of Python expression set(dict.keys()).issubset(set(list))
.
Only string or unicode dictionary keys are supported.
Tags: c_interface, python