How can we read Python dictionary using C++?

A dictionary in Python is a collection of key-value pairs where each key must be unique. Unlike lists which are indexed by numbers, dictionaries are accessed using keys that can be immutable types like strings, numbers, or tuples. Lists cannot be used as keys because they can be modified.

Dictionaries are created using {}, and key-value pairs are added with commas. We can store, retrieve, and delete values using their keys. To check if a key exists, we can use the in keyword.

Reading Python Dictionaries using C++

There are several C++/Python bindings available for facilitating communication between the two languages to read Python dictionaries in C++. Many libraries, such as Boost.Python, handle parsing automatically. Alternatively, we can use intermediate data transfer formats like JSON or XML to exchange data between C++ and Python through serialization and deserialization functions.

Method 1: Using Python C/API

We can integrate Python into our C++ code to work with Python objects, including dictionaries. This approach requires initializing the Python interpreter within our C++ program, then using the Python/C API to execute Python code and access dictionary objects ?

#include <Python.h>
#include <iostream>

int main() {
    // Initialize Python interpreter
    Py_Initialize();

    // Execute Python code that creates a dictionary
    PyRun_SimpleString("my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}");
    
    // Get reference to the main module
    PyObject* main_module = PyImport_AddModule("__main__");
    PyObject* global_dict = PyModule_GetDict(main_module);

    // Get the dictionary object from Python
    PyObject* py_dict = PyDict_GetItemString(global_dict, "my_dict");

    // Check if it's a valid dictionary and iterate
    if (PyDict_Check(py_dict)) {
        PyObject *key, *value;
        Py_ssize_t pos = 0;

        std::cout << "Reading Python dictionary in C++:" << std::endl;
        while (PyDict_Next(py_dict, &pos, &key, &value)) {
            const char* key_str = PyUnicode_AsUTF8(key);
            
            // Handle different value types
            if (PyLong_Check(value)) {
                long val = PyLong_AsLong(value);
                std::cout << key_str << ": " << val << std::endl;
            } else if (PyUnicode_Check(value)) {
                const char* val_str = PyUnicode_AsUTF8(value);
                std::cout << key_str << ": " << val_str << std::endl;
            }
        }
    }

    // Clean up Python interpreter
    Py_Finalize();
    return 0;
}

The output of the above code would be ?

Reading Python dictionary in C++:
name: Alice
age: 25
city: New York

Method 2: Using JSON Serialization

JSON serialization provides a simpler approach for data exchange between Python and C++. Python can serialize the dictionary to JSON, and C++ can parse the JSON string ?

Python Side (serialize_dict.py)

import json

# Create a Python dictionary
data = {
    'users': ['Alice', 'Bob', 'Charlie'],
    'count': 3,
    'active': True
}

# Serialize to JSON and save to file
with open('data.json', 'w') as f:
    json.dump(data, f)

print("Dictionary serialized to JSON")

C++ Side (with JSON library)

#include <iostream>
#include <fstream>
#include <string>
// Note: This example assumes using a JSON library like nlohmann/json

int main() {
    std::ifstream file("data.json");
    std::string json_str((std::istreambuf_iterator<char>(file)),
                         std::istreambuf_iterator<char>());
    
    std::cout << "JSON data from Python dictionary:" << std::endl;
    std::cout << json_str << std::endl;
    
    // Parse JSON and extract values using JSON library
    // auto json_data = json::parse(json_str);
    // std::cout << "Count: " << json_data["count"] << std::endl;
    
    return 0;
}

Comparison

Method Complexity Performance Best For
Python C/API High Fast Direct embedding
JSON Serialization Low Moderate Cross-language communication
Boost.Python Medium Fast Complex integrations

Conclusion

Use Python C/API for direct embedding and high performance. For simpler cross-language communication, JSON serialization provides an easier approach with good compatibility.

Updated on: 2026-03-24T20:27:37+05:30

686 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements