Medical physicist
Medical physicist

Reputation: 2594

Nested dict and pybind11

I have a C++ extension bundled with Python by using pybind11. The extension returns a nested Python dict object:

#include <pybind11/pybind11.h>
namespace py = pybind11;

py::dict cpp_ext(void)  {
    // Variables
    py::dict res;

    // Result
    res["circle"]["x0"] = 0;
    res["circle"]["y0"] = 0;
    res["circle"]["r"] = 1;
    return res;
};

It compiles, but gives me the error:

KeyError: ('circle',)

How should I construct a nested py::dict object ?

Upvotes: 0

Views: 1629

Answers (1)

a_guest
a_guest

Reputation: 36249

You can create a separate dict for the nested instance and then assign it to the outer one:

py::dict cpp_ext(void)  {
    // Variables
    py::dict res;
    py::dict circle;

    // Result
    circle["x0"] = 0;
    circle["y0"] = 0;
    circle["r"] = 1;
    res["circle"] = circle;
    return res;
};

Upvotes: 3

Related Questions