CPython - read a Python dictionary (keys / values) inside a C function. Passed as argument

I am writing a Python C extension. I am passing a Python dictionary to a C function. I can parse it using the following code:

PyObject *large_dict = NULL; if (! PyArg_ParseTuple( args, "O!", &PyDict_Type, &large_dict)) return NULL; if (large_dict != NULL) { printf("Large Dictionary Not Null\n"); } 

The expression "Big Dictionary is not zero" is printed here, which means that the dictionary is being successfully analyzed. Now I want to access the values ​​of the dictionary by specifying keys, for example, in python. those. dict ['k1'] and this gives the value v1.

How can I access the keys / values ​​of a dictionary inside this C function?

Please suggest me a solution?

+5
source share
1 answer

You must go through the link, https://docs.python.org/2/c-api/dict.html Excerpt below

 PyObject* PyDict_GetItem(PyObject *p, PyObject *key) Return value: Borrowed reference. Return the object from dictionary p which has a key key. Return NULL if the key key is not present, but without setting an exception. PyObject* PyDict_GetItemString(PyObject *p, const char *key) Return value: Borrowed reference. This is the same as PyDict_GetItem(), but key is specified as a char*, rather than a PyObject*. PyObject* PyDict_Items(PyObject *p) Return value: New reference. Return a PyListObject containing all the items from the dictionary, as in the dictionary method dict.items(). PyObject* PyDict_Keys(PyObject *p) Return value: New reference. Return a PyListObject containing all the keys from the dictionary, as in the dictionary method dict.keys(). PyObject* PyDict_Values(PyObject *p) Return value: New reference. Return a PyListObject containing all the values from the dictionary p, as in the dictionary method dict.values(). 

Watch out for the borrowed reference / new reference . This is a bit complicated when coding Python extensions.

+5
source

Source: https://habr.com/ru/post/1239117/


All Articles