Skip to content

Can I programmatically add to pybind11::dict ? #5197

Answered by jiwaszki
nyue asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @nyue , it is for sure possible! You just need everything to be converted to Python objects, example:

    m.def("get_custom_dict", []() {
        py::dict my_dict;

        my_dict[py::str("triple")] = py::str("H");
        my_dict[py::int_(3)] = py::int_(16);
        my_dict[py::int_(42)] = py::str("abc");

        return my_dict;
    });

Here are results in Python:

In [1]: import mymodule
   ...: print(mymodule.get_custom_dict())
   ...: 
{'triple': 'H', 3: 16, 42: 'abc'}

Just remember that py::dict itself is collection of Python objects that "works on Python side", i.e. you need to capture GIL before using it. Thus all the keys and values are required to be "on Python side" as well.…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@marcingretl
Comment options

Answer selected by nyue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants