C API - How to return a Dictionary as a Dictionary type

Jen Kris jenkris at tutanota.com
Mon Feb 14 20:05:42 EST 2022


I created a dictionary with the Python C API and assigned two keys and values:

PyObject* this_dict = PyDict_New(); 
const char *key = "key1";
char *val = "data_01"; 
PyObject* val_p = PyUnicode_FromString(val); 
int r = PyDict_SetItemString(this_dict, key, val_p); 

// Add another k-v pair
key = "key2";
val = "data_02"; 
val_p = PyUnicode_FromString(val); 
r = PyDict_SetItemString(this_dict, key, val_p); 

I need to retrieve the entire dictionary to be passed to a library function that expects a dictionary.  I used  PyDict_Items:

PyObject* pdi = PyDict_Items(this_dict);
PyObject* str_untagd = PyObject_Str(pdi);
PyObject* repr_utd = PyObject_Repr(str_untagd);
PyObject* str_utd = PyUnicode_AsEncodedString(repr_utd, "utf-8", "~E~");  
const char *bytes_d = PyBytes_AS_STRING(str_utd);
printf("REPR_UnTag: %s\n", bytes_d);

but as the docs say (https://docs.python.org/3.8/c-api/dict.html), that returns a PyListObject, not a dictionary enclosed with curly braces: 

[('key1', 'data_01'), ('key2', 'data_02')]". 

My question is, how can I get the dictionary as a dictionary type, enclosed with curly braces.  I found PyObject_GenericGetDict (https://docs.python.org/3.8/c-api/object.html) but I haven't found any documentation or explanation of how it works. 

Is PyObject_GenericGetDict what I need, or is there another way to do it?


Thanks,

Jen




More information about the Python-list mailing list