Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a hashmap by values in rust

Tags:

rust

In python its done this way:

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}

{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

How to sort a HashMap by values in rust?

My code so far:

use std::collections::HashMap;

fn main() {
    let mut count: HashMap<String, u32>= HashMap::new();
    count.insert(String::from("A"), 5);
    count.insert(String::from("B"), 2);
    count.insert(String::from("C"), 11);
    count.insert(String::from("D"), 10);

    let highest = count.iter().max_by(|a, b| a.1.cmp(&b.1)).unwrap();

    println!("largest hash: {:?}", highest); // largest hash: ("C", 11)
}
like image 496
Amiya Behera Avatar asked Sep 02 '25 16:09

Amiya Behera


1 Answers

Ya, sorted it by converting to vector:

use std::collections::HashMap;

fn main() {
    let mut count: HashMap<String, u32>= HashMap::new();
    count.insert(String::from("A"), 5);
    count.insert(String::from("B"), 2);
    count.insert(String::from("C"), 11);
    count.insert(String::from("D"), 10);

    let mut hash_vec: Vec<(&String, &u32)> = count.iter().collect();
    println!("{:?}", hash_vec);
    hash_vec.sort_by(|a, b| b.1.cmp(a.1));

    println!("Sorted: {:?}", hash_vec); //Sorted: [("C", 11), ("D", 10), ("A", 5), ("B", 2)]
}

Sort HashMap data by value

like image 182
Amiya Behera Avatar answered Sep 04 '25 07:09

Amiya Behera