Repository navigation
|
Instead of initializing a pybind11::dict like this auto locals = pybind11::dict("name"_a="World", "number"_a=42);Can I create an empty dictionary and add elements programmatically ? What is the method name for inserting new item ? auto locals = pybind11::dict(); |
Answered by
jiwaszki
Jul 16, 2024
Replies: 1 comment 1 reply
|
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 PS I hope that you managed to find it sooner! Cheers! |
1 reply
Answer selected by
nyue
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @nyue , it is for sure possible! You just need everything to be converted to Python objects, example:
Here are results in Python:
Just remember that
py::dictitself 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.…