typestar

Dictionaries in Mojo

Key-value storage with a declared key type and value type.

def main() raises:
    var stock = Dict[String, Int]()
    stock["apples"] = 12
    stock["pears"] = 4
    # Reading a key can fail, so main is marked raises.
    stock["apples"] += 3
    print(len(stock), stock["apples"])
    print("pears" in stock, "figs" in stock)

How it works

  1. Dict[String, Int]() creates an empty map.
  2. Assignment adds or replaces a key, and += reads then writes.
  3. Reading a key can fail, so main carries raises; in cannot fail.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
239
Tokens
66
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 3 of 6 in Collections, step 14 of 26 in Language basics.

← Previous Next →

Dictionaries in other languages