Answer#
A Python dictionary does three different jobs, and the port depends on which one a given dict does:
| Python | Rust |
|---|---|
A record with fixed field names ({"name": ..., "id": ...}) | a struct with those fields |
| A lookup table from keys known only at run time | HashMap<K, V> (or BTreeMap for sorted keys) |
| A field that can be a number or a string | an enum with one variant per case |
A field that may be missing or None | Option<T> |
| A list of mixed items | an 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:
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)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:
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}");
}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 21A 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#
- 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.
- Write the structs and enums to match. Use
Option<T>for optional fields (serde fillsNone), and#[serde(default)]for fields that should default when missing. - Parse at the edge:
serde_json::from_strfor JSON. Do the conversion once, then pass typed values inward. - For genuinely free-form data (a plugin's settings),
serde_json::Valueis 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. - Port duck typing ("anything with a
.read()") to a trait that declares the method.
Common mistakes#
- Using
serde_json::Valueeverywhere to avoid designing types. It works, but you lose the checks that were the reason to port. - Using
untaggedenums 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.
Related questions#
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#
- Serde documentation, "Enum representations": https://serde.rs/enum-representations.html
serde_json::Value: https://docs.rs/serde_json/latest/serde_json/enum.Value.html