typestar

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

  1. for entry in scores.items(): walks every pair once.
  2. entry.key and entry.value read the two sides.
  3. The loop prints each score and accumulates the total.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 6 in Collections, step 15 of 26 in Language basics.

← Previous Next →