用C++打印python字典里面的内容
时间: 2023-07-12 19:28:10 浏览: 158
python 字典的打印实现
要在C++中打印Python字典中的内容,需要使用Python C API,以下是一个简单的示例代码:
```c++
#include <Python.h>
int main() {
Py_Initialize();
// 创建一个Python字典
PyObject* dict = PyDict_New();
PyDict_SetItemString(dict, "key1", PyUnicode_FromString("value1"));
PyDict_SetItemString(dict, "key2", PyUnicode_FromString("value2"));
PyDict_SetItemString(dict, "key3", PyUnicode_FromString("value3"));
// 打印字典中的所有键和值
PyObject* keys = PyDict_Keys(dict);
for (Py_ssize_t i = 0; i < PyList_Size(keys); ++i) {
PyObject* key = PyList_GetItem(keys, i);
PyObject* value = PyDict_GetItem(dict, key);
printf("%s: %s\n", PyUnicode_AsUTF8(key), PyUnicode_AsUTF8(value));
}
Py_DECREF(dict);
Py_DECREF(keys);
Py_Finalize();
return 0;
}
```
请注意,在使用Python C API之前,需要先调用`Py_Initialize()`来初始化Python解释器,并在使用完Python对象后调用`Py_DECREF()`来释放它们的内存。
阅读全文