FAQ - Help and questions

How do I port Python dictionaries and dynamic types to Rust?

#porting#python#serdepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A Python dict used as a record becomes a struct, and a dict whose keys are not known in advance becomes a HashMap. A value that may be an int or a string becomes an enum. With serde, JSON input is checked once at the edge, so typos and wrong shapes are errors there instead of KeyError later.

Checked with rustc 1.93.0, serde 1.0.229, serde_json 1.0.154, Python 3.13.7, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A Python dictionary does three different jobs, and the port depends on which one a given dict does:

PythonRust
A record with fixed field names ({"name": ..., "id": ...})a struct with those fields
A lookup table from keys known only at run timeHashMap<K, V> (or BTreeMap for sorted keys)
A field that can be a number or a stringan enum with one variant per case
A field that may be missing or NoneOption<T>
A list of mixed itemsan enum item type in a Vec, or a Vec per kind

The Python program uses one dict in all those ways and shows the run-time failure of a misspelled key:

python
user = {"name": "Ada", "id": "u-7", "scores": {"math": [90, 80], "art": [70]}}
print(user["name"], sorted(user["scores"]), sum(user["scores"]["math"]))
try:
    print(user["nmae"])
except KeyError as e:
    print("KeyError at run time:", e)
text
Ada ['art', 'math'] 170
KeyError at run time: 'nmae'

The Rust port with serde (serde with the derive feature, and serde_json) turns the shape into types. The field id is an enum because it may be a number or text, and scores is a map because its subjects are not known in advance:

src/main.rsrust
use serde::Deserialize;
use std::collections::HashMap;

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Id {
    Number(u64),
    Text(String),
}

#[derive(Debug, Deserialize)]
struct User {
    name: String,
    id: Id,
    #[serde(default)]
    scores: HashMap<String, Vec<u32>>, // keys are not known in advance: a real map
}

fn main() {
    let text = r#"{"name":"Ada","id":"u-7","scores":{"math":[90,80],"art":[70]}}"#;
    let u: User = serde_json::from_str(text).unwrap();
    println!("{} {:?}", u.name, u.id);
    let mut keys: Vec<_> = u.scores.keys().collect();
    keys.sort();
    println!("{keys:?}");
    println!("{}", u.scores["math"].iter().sum::<u32>());

    // a typo in a field name is a compile error (u.nmae), and a missing field in the input is an error value:
    let e = serde_json::from_str::<User>(r#"{"id":1}"#).unwrap_err();
    println!("{e}");
    let n = serde_json::from_str::<User>(r#"{"name":"x","id":1.5}"#).unwrap_err();
    println!("{n}");
}
text
Ada Text("u-7")
["art", "math"]
170
missing field `name` at line 1 column 8
data did not match any variant of untagged enum Id at line 1 column 21

A misspelled field name in Rust code (u.nmae) does not compile. A wrong shape in the input is reported where the data enters the program, with a position. Note that the map's keys come out in no fixed order, so the example sorts them before printing (see the thread on key order).

How to do it#

  1. Collect real examples of the dicts (log them, or read the test data) and write down for each key: always present or optional, which types.
  2. Write the structs and enums to match. Use Option<T> for optional fields (serde fills None), and #[serde(default)] for fields that should default when missing.
  3. Parse at the edge: serde_json::from_str for JSON. Do the conversion once, then pass typed values inward.
  4. For genuinely free-form data (a plugin's settings), serde_json::Value is the dynamic type: it is Python's dict, list, string, number, bool and None as an enum. Use it only where you cannot know the shape.
  5. Port duck typing ("anything with a .read()") to a trait that declares the method.

Common mistakes#

  • Using serde_json::Value everywhere to avoid designing types. It works, but you lose the checks that were the reason to port.
  • Using untagged enums for large inputs: the error message is vague (as above), because serde tries each variant in turn. Prefer a tag field in data you control.
  • Forgetting that Python ints have no size limit and Rust ints do. Pick the width the data really needs, and see the JavaScript numbers thread for the same issue in JSON.

What replaces dict.get(key, default)?#

map.get(key).copied().unwrap_or(default) for plain values, or map.entry(key).or_insert(default) to insert as well.

What replaces collections.defaultdict?#

map.entry(key).or_default() returns a mutable reference to the value, creating it first when missing.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet