Search code examples
rustpyo3

How to create a heterogeneous Python dict in Rust with PyO3?


Based on this I can create a homogeneous Python dictionary.

How can I create a dictionary with mixed-type values, e.g. make this work:

let dict = [ ("num", 8), ("str", "asd") ].into_py_dict(py);

?


Solution

  • I'm not a user of pyo3, but from Rust's point of view the problem is that you try to make a heterogeneous array, which is prohibited anyway. To solve it you may try to convert it into a homogeneous array by utilizing PyObject type of the crate. I can't test if the next snippet works and I'm not sure if you can make it simpler, but the idea holds:

    let key_vals: &[(&str, PyObject)] = [ ("num", 8.to_object()), ("str", "asd".to_object()) ]
    let dict = key_vals.into_py_dict(py);