1

I have a dictionary which in python I can iterate using

data = {"one":1,"two":2,"three":3,"four":4,....."two hundred":200}

for i,j in data.items():
    print(i,j)

Is there any way I can use the same object and iterate over the keys and values in rust?

2
  • for (i, j) in data (i and j are owned values) or for (r, s) in &data (r and s are references) Commented Feb 18, 2021 at 13:23
  • Are you asking about Rust syntax for the same thing? Or by "same object" do you mean accessing the Python object from Rust using PyO3 or something? Commented Feb 18, 2021 at 13:24

2 Answers 2

9

I'm assuming you're after a way to do this in Rust.

Rust's analogue to a Python dictionary is a HashMap.

Unlike Python's dictionaries HashMaps are statically typed (i.e. all the keys must have the same type, and all the values must also share the same type) – to create a new HashMap you want something like:

use std::collections::HashMap;

fn main() {
  let mut hashmap: HashMap<String, i32> = HashMap::new();
  hashmap.insert("one".to_string(), 1);
  for (key, value) in hashmap {
      println!("{} {}", key, value);
  }
}

Which outputs:

one 1

Playground link

If you want to load the object from Python into Rust, there are a couple of options

  • You can serialize the object in the Python process and then use serde to deserialize it on the Rust side.

  • You can bind to CPython (e.g. using PyO3).

Sign up to request clarification or add additional context in comments.

Comments

3

This works for me

use serde_json::json;

fn main() {
          
    let data = json!({"one":1,"two":2,"three":3,"four":4});    

    for (key, value) in data.as_object().unwrap(){
        println!("{:?} : {:?}",key,value.as_u64().unwrap());
    }
}

1 Comment

However, HashMap is a direct replacement of a Dicts from Puthon, your solution looks most "pythonic" analog to what dicts feels in Python. Thx!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.