Skip to content

Mojo Dictionaries

A dictionary stores pairs: a key and the value that belongs to it. Instead of asking “what’s at position 2?” like you do with a list, you ask “what’s the value for "Ada"?”. Mojo’s dictionary type is Dict, and it behaves a lot like Python’s dict. The main differences are that every key has one type and every value has one type, and that looking up a missing key is an error you have to plan for.

Write the pairs in curly braces, with a colon between each key and its value:

def main():
var ages = {"Ada": 36, "Bo": 9, "Cy": 21}
print(ages)
print(len(ages))

Output:

{Ada: 36, Bo: 9, Cy: 21}
3

Mojo works out the type from the literal: this is a Dict[String, Int], a dictionary with String keys and Int values. len() tells you how many pairs it holds. You don’t need an import for Dict; it’s always available.

To start empty, give the types yourself, because there’s nothing for Mojo to look at:

def main():
var stock = Dict[String, Int]()
var prices: Dict[String, Float64] = {}
print(stock, prices, len(stock))

Output:

{} {} 0

Both lines make an empty dictionary. Use whichever reads better to you.

Square brackets do all three jobs. Assigning to a key that doesn’t exist adds it. Assigning to a key that exists replaces its value:

def main() raises:
var stock = Dict[String, Int]()
stock["apples"] = 10
stock["pears"] = 4
stock["apples"] = 12
print(stock)
print(stock["pears"])

Output:

{apples: 12, pears: 4}
4

Notice the raises after def main(). Reading with stock["pears"] can raise an error, because the key might not be there. Mojo makes you deal with that: either mark the function raises or put the lookup in a try block. Without either, the program doesn’t compile and the message says “cannot call function that may raise in a context that cannot raise”.

Here’s what happens when the key really is missing:

def main() raises:
var stock = {"apples": 12}
print(stock["kiwis"])
Unhandled exception caught during execution: DictKeyError[String]()
mojo: error: execution exited with a non-zero result: 1

The program stops with a DictKeyError. In Python this would be a KeyError. It’s the same idea, but the message doesn’t tell you which key was missing, so it pays to check first.

Most of the time you don’t want the program to stop. There are three safe ways to ask for a key:

def main():
var stock = {"apples": 12, "pears": 4}
if "kiwis" in stock:
print("we have kiwis")
else:
print("no kiwis")
print(stock.get("pears", 0))
print(stock.get("kiwis", 0))
var maybe = stock.get("kiwis")
print(maybe)
print(maybe.or_else(-1))

Output:

no kiwis
4
0
None
-1
  • key in d tells you whether a key exists.
  • d.get(key, default) gives you the value, or the default if the key is missing. This is the one you’ll use most.
  • d.get(key) with no default gives you an Optional: a box that either holds the value or holds nothing (None). or_else() takes the value out, or uses a fallback. Mojo Optional covers this type properly.

None of these can raise, so this main doesn’t need raises.

A very common job for a dictionary is counting. get with a default makes it short:

def main():
var words: List[String] = ["red", "blue", "red", "green", "red", "blue"]
var counts = Dict[String, Int]()
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)

Output:

{red: 3, blue: 2, green: 1}

The first time a word shows up, get returns 0, so the count becomes 1. After that it adds one to the count that’s already there.

pop removes a key and gives you back its value:

def main() raises:
var cart = {"milk": 2, "eggs": 12, "tea": 1}
var eggs = cart.pop("eggs")
print("removed eggs:", eggs)
print(cart.pop("bread", 0))
print(cart)
cart.clear()
print(cart)

Output:

removed eggs: 12
0
{milk: 2, tea: 1}
{}

pop(key) raises if the key is missing, just like d[key]. pop(key, default) returns the default instead, so it’s safe. clear() removes every pair.

You can loop over the keys, the values, or both:

def main():
var capitals = {"France": "Paris", "Japan": "Tokyo", "Peru": "Lima"}
for country in capitals.keys():
print(country)
for city in capitals.values():
print(city)
for item in capitals.items():
print(item.key, "->", item.value)

Output:

France
Japan
Peru
Paris
Tokyo
Lima
France -> Paris
Japan -> Tokyo
Peru -> Lima

Two things to notice:

  • The order is the order you added the keys. Like Python 3.7 and later, Mojo’s Dict promises this, and changing a value doesn’t move its key.
  • items() gives you entries with .key and .value fields. A plain for x in capitals loops over the keys, the same as .keys().

To change values while you loop, use ref, the same way you do with lists:

def main():
var prices = {"tea": 3, "cake": 5}
for ref p in prices.values():
p += 1
print(prices)

Output:

{tea: 4, cake: 6}

update() copies all pairs from another dictionary into this one. The | operator makes a new merged dictionary and leaves both inputs alone:

def main():
var defaults = {"color": "blue", "size": "M"}
var choices = {"size": "L"}
var merged = defaults | choices
print(merged)
print(defaults)
defaults.update(choices)
print(defaults)

Output:

{color: blue, size: L}
{color: blue, size: M}
{color: blue, size: L}

When both have the same key, the value from the right-hand side wins, like in Python.

Like a list, a dictionary is a value that owns its contents, and var b = a is a compile error (“cannot be implicitly copied”). Ask for a copy when you want one:

def main():
var original = {"a": 1}
var backup = original.copy()
backup["b"] = 2
print(original, backup)

Output:

{a: 1} {a: 1, b: 2}

Keys must be values Mojo knows how to hash and compare: Int, String, Bool and tuples of those all work. Values can be almost anything, even a list:

def main() raises:
var groups = Dict[String, List[String]]()
groups["fruit"] = ["apple"]
groups["fruit"].append("fig")
groups["veg"] = ["leek"]
print(groups)
var board = Dict[Tuple[Int, Int], String]()
board[(0, 1)] = "tree"
print(board[(0, 1)], (2, 2) in board)

Output:

{fruit: [apple, fig], veg: [leek]}
tree False

groups["fruit"].append("fig") changes the list that’s stored inside the dictionary. The tuple keys in board are a handy way to store things on a grid. Tuples get their own lesson in Mojo Tuples. The Dict API docs list the exact rules and every method, including setdefault() and popitem().

Python Mojo
Make one d = {"a": 1} var d = {"a": 1}
Empty one d = {} var d = Dict[String, Int]()
Missing key with d[k] KeyError DictKeyError; the function needs raises or try
Safe lookup d.get(k, 0) Same
d.get(k) with no default The value or None An Optional
Loop over pairs for k, v in d.items() for item in d.items(), then item.key, item.value
b = a Same dict, two names Error: use a.copy()

Count how many times each letter appears in the list ["m", "o", "j", "o", "o"], then print the count for "o" and for "z" (which isn’t there, so it should print 0).

Hint: use counts.get(letter, 0) + 1 to count, and get with a default to read.

Show solution
def main():
var letters: List[String] = ["m", "o", "j", "o", "o"]
var counts = Dict[String, Int]()
for letter in letters:
counts[letter] = counts.get(letter, 0) + 1
print(counts)
print("o:", counts.get("o", 0))
print("z:", counts.get("z", 0))

Output:

{m: 1, o: 3, j: 1}
o: 3
z: 0

Reading with get(key, 0) means a missing letter gives 0 instead of an error, so main doesn’t need raises.

Make a dictionary of prices: "tea" is 3, "cake" is 5, "soup" is 7. Loop over it and print each item as tea costs 3. Then print the total of all prices.

Hint: loop over items() and use item.key and item.value.

Show solution
def main():
var prices = {"tea": 3, "cake": 5, "soup": 7}
var total = 0
for item in prices.items():
print(item.key, "costs", item.value)
total += item.value
print("total:", total)

Output:

tea costs 3
cake costs 5
soup costs 7
total: 15

The items come out in the order they were added, so the output is the same every time you run it.

This program should print each country and its capital. It doesn’t compile. Fix it.

def main():
var capitals = {"Kenya": "Nairobi", "Chile": "Santiago"}
for country, city in capitals.items():
print(country, city)

Hint: each item from items() isn’t a tuple.

Show solution
def main():
var capitals = {"Kenya": "Nairobi", "Chile": "Santiago"}
for item in capitals.items():
print(item.key, item.value)

Output:

Kenya Nairobi
Chile Santiago

Mojo’s dictionary entries have .key and .value fields, so you loop over the items and read those instead of unpacking.

  • A dictionary maps keys to values: var d = {"Ada": 36} is a Dict[String, Int]. An empty one needs its types: Dict[String, Int]().
  • d[key] = value adds or updates. d[key] reads, and raises if the key is missing.
  • Look up safely with key in d, d.get(key, default), or d.get(key), which gives an Optional.
  • pop(key) removes a pair (it raises if missing); pop(key, default) doesn’t.
  • Loop with keys(), values() and items(). Items have .key and .value, and they come out in insertion order.
  • Merge with update() or |, and copy with .copy().

Next up: sets, for keeping a group of unique values and checking membership fast.

Quick check

1. What happens when you read d["x"] and the key "x" is not in the dictionary?
2. Which lookup never raises and gives you a fallback value?
3. How do you loop over the pairs of a Dict in Mojo?
4. In what order does a Dict give you its keys?