Iterating a dictionary in Mojo
items() yields entries that carry both halves of the pair.
def main():
var scores = Dict[String, Int]()
scores["ada"] = 91
scores["alan"] = 84
scores["grace"] = 97
var total = 0
for entry in scores.items():
print(entry.key, "scored", entry.value)
total += entry.value
print("total", total)
How it works
for entry in scores.items():walks every pair once.entry.keyandentry.valueread the two sides.- The loop prints each score and accumulates the total.
Keywords and builtins used here
IntStringdefformainprintvar
The run, in numbers
- Lines
- 10
- Characters to type
- 230
- Tokens
- 75
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 56 seconds.
Step 4 of 6 in Collections, step 15 of 26 in Language basics.