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.
Making a dictionary
Section titled “Making a dictionary”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}3Mojo 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:
{} {} 0Both lines make an empty dictionary. Use whichever reads better to you.
Adding, changing and reading values
Section titled “Adding, changing and reading values”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}4Notice 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: 1The 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.
Looking up safely
Section titled “Looking up safely”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 kiwis40None-1key in dtells 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 anOptional: 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.
Counting things
Section titled “Counting things”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.
Removing pairs
Section titled “Removing pairs”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: 120{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.
Looping over a dictionary
Section titled “Looping over a dictionary”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:
FranceJapanPeruParisTokyoLimaFrance -> ParisJapan -> TokyoPeru -> LimaTwo things to notice:
- The order is the order you added the keys. Like Python 3.7 and later, Mojo’s
Dictpromises this, and changing a value doesn’t move its key. items()gives you entries with.keyand.valuefields. A plainfor x in capitalsloops 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}Merging dictionaries
Section titled “Merging dictionaries”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.
Copying a dictionary
Section titled “Copying a dictionary”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}What can be a key?
Section titled “What can be a key?”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 Falsegroups["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().
Coming from Python?
Section titled “Coming from Python?”| 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() |
Practice
Section titled “Practice”1. Letter count
Section titled “1. Letter count”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: 3z: 0Reading with get(key, 0) means a missing letter gives 0 instead of an error, so main doesn’t need raises.
2. Price list
Section titled “2. Price list”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 3cake costs 5soup costs 7total: 15The items come out in the order they were added, so the output is the same every time you run it.
3. Fix the program
Section titled “3. Fix the program”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 NairobiChile SantiagoMojo’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 aDict[String, Int]. An empty one needs its types:Dict[String, Int](). d[key] = valueadds or updates.d[key]reads, and raises if the key is missing.- Look up safely with
key in d,d.get(key, default), ord.get(key), which gives anOptional. pop(key)removes a pair (it raises if missing);pop(key, default)doesn’t.- Loop with
keys(),values()anditems(). Items have.keyand.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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Dict API docs: every method, the rules for keys, and notes on iteration.
- Mojo manual: Types: the official short introduction to
Dictand the other collections. - Mojo manual: Errors: how
raises,tryandexceptwork, for handling missing keys. - Mojo tips for Python developers: where Python dictionary habits carry over and where they don’t.