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

Chris Angelico rosuav at gmail.com
Mon Feb 14 20:24:31 EST 2022


On Tue, 15 Feb 2022 at 12:07, Jen Kris via Python-list
<python-list at python.org> wrote:
>
> 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?
>

Not sure what you mean. The dict is already a dict. If you refer to
this_dict, it is a dict, right?

If you need the string representation of that, you should be able to
call PyObject_Repr just as you are, but call it on the dict, not on
the dict items.

ChrisA


More information about the Python-list mailing list