Associative array/Iteration: Difference between revisions

Content added Content deleted
(→‎{{header|TXR}}: Dop @(do ...), remove spurious argument in [h k nil], streamline.)
(→‎{{header|Rust}}: Made example match the creating assiociated array example)
Line 2,135: Line 2,135:
=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>use std::collections::HashMap;
<lang Rust>use std::collections::HashMap;

fn main() {
fn main() {
let mut squares = HashMap::new();
let mut olympic_medals = HashMap::new();
squares.insert("one", 1);
olympic_medals.insert("United States", (1072, 859, 749));
squares.insert("two", 4);
olympic_medals.insert("Soviet Union", (473, 376, 355));
squares.insert("three", 9);
olympic_medals.insert("Great Britain", (246, 276, 284));
olympic_medals.insert("Germany", (252, 260, 270));
for key in squares.keys() {
for (country, medals) in olympic_medals {
println!("Key {}", key);
println!("{} has had {} gold medals, {} silver medals, and {} bronze medals",
}
country, medals.0, medals.1, medals.2);
for value in squares.values() {
println!("Value {}", value);
}
for (key, value) in squares.iter() {
println!("{} => {}", key, value);
}
}
}</lang>
}</lang>
{{out}}
{{out}}
Note that <code>HashMap</code> does not preserve order (if this is important, <code>std::collections::BTreeMap</code> is what you want.)
<pre>
<pre>
Germany has had 252 gold medals, 260 silver medals, and 270 bronze medals
Key three
United States has had 1072 gold medals, 859 silver medals, and 749 bronze medals
Key two
Soviet Union has had 473 gold medals, 376 silver medals, and 355 bronze medals
Key one
Great Britain has had 246 gold medals, 276 silver medals, and 284 bronze medals
Value 9
Value 4
Value 1
three => 9
two => 4
one => 1
</pre>
</pre>