Ordering an hashmap

I have a vector of hashmaps whose key value pairs are unordered.
For example :
let details = vec![{"lastname": "Pichai", "marks": "", "firstname": "Sirish", "number": "1", "maths": "77", "physics": "68", "chemistry": "43"},
{"chemistry": "63", "marks": "65.4", "firstname": "Krishna", "physics": "78", "maths": "50", "number": "2", "lastname": "Sharma"},
{"maths": "60", "number": "3", "lastname": "Akkineni", "physics": "78", "chemistry": "56", "marks": "78.4", "firstname": "Ram"}];

Now, I want to all the hashmaps in the vector to be ordered as per an order, say as in the below vector:

let headers = vec!["number", "firstname", "lastname", "maths", "physics", "chemistry", "marks"];

How can I arrange them ?

Iterate the headers, map each to their value from the hashmap, and collect that to a new vector.

Or you can use the indexmap crate to keep them in insertion order in the first place.

Would the fields be "ordered" if they were from a struct as opposed to a hashmap?

struct Student {
    number: usize,
    ...
    marks: f32,
}

Also, guessing what kind of task you're up to, serde may be worth a look as an excellent library for serialisation to/from such a struct.
A quick search shows some others have gone down similar roads with serde, hashmaps and ordering: https://stackoverflow.com/questions/42723065/how-to-sort-hashmap-keys-when-serializing-with-serde

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.