Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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);

?

like image 521
tungli Avatar asked Mar 01 '23 22:03

tungli


2 Answers

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);
like image 183
Alexey Larionov Avatar answered Mar 05 '23 19:03

Alexey Larionov


Just for completion -- Alex Larionov's idea works!

The working code snippet is:

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

The whole main here.

This additional import is needed:

use pyo3::types::IntoPyDict;

Also, just a remark, if you happen to need to put a Python None value into the dictionary, where .to_object(py) fails, use:

py.None()

instead.

Variable py is the pyo3::Python object.

like image 35
tungli Avatar answered Mar 05 '23 19:03

tungli