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
Dict[String, Int]()creates an empty map.- Assignment adds or replaces a key, and
+=reads then writes. - Reading a key can fail, so
maincarriesraises;incannot fail.
Keywords and builtins used here
IntStringdeflenmainprintvar
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.
Step 3 of 6 in Collections, step 14 of 26 in Language basics.