Mojo Dictionaries

A dictionary stores data as key-value pairs. You look up a value by providing its key — like looking up a word in a physical dictionary to find its definition. Mojo's Dict type gives you fast lookups, insertions, and deletions regardless of how many items the dictionary holds.

The Phone Book Analogy

  Physical Phone Book          Dictionary in Mojo
  ────────────────────         ──────────────────────────
  Name → Number                Key   → Value
  ──────────────               ──────────────────────────
  Alice → 555-1234             "Alice" → "555-1234"
  Bob   → 555-5678             "Bob"   → "555-5678"
  Carol → 555-9012             "Carol" → "555-9012"

  You look up "Bob" and       You provide key "Bob"
  instantly find his number.  and get "555-5678" back.

Creating a Dictionary

from collections import Dict

fn main():
    var phone_book = Dict[String, String]()
    phone_book["Alice"] = "555-1234"
    phone_book["Bob"]   = "555-5678"
    phone_book["Carol"] = "555-9012"

    print(phone_book["Alice"])   # 555-1234
    print(phone_book["Bob"])     # 555-5678

The two types in Dict[String, String] specify the key type and the value type. Keys must all share one type; values must all share one type.

Common Key-Value Type Combinations

Dict[String, Int]     → word → frequency count
Dict[String, Float64] → city → temperature
Dict[String, String]  → name → phone number
Dict[Int, String]     → employee ID → name

Checking if a Key Exists

Accessing a missing key causes a runtime error. Always check before accessing.

from collections import Dict

fn main():
    var scores = Dict[String, Int]()
    scores["Priya"] = 88
    scores["Leo"]   = 74

    if "Priya" in scores:
        print("Priya's score:", scores["Priya"])   # 88

    if "Sam" in scores:
        print("Sam found")
    else:
        print("Sam is not in the dictionary")

Updating Values

Assign to an existing key to overwrite its value. The dictionary keeps exactly one entry per key.

from collections import Dict

fn main():
    var stock = Dict[String, Int]()
    stock["apple"]  = 50
    stock["banana"] = 30

    # A shipment arrives
    stock["apple"] += 20   # now 70
    print(stock["apple"])  # 70
Before update: {"apple": 50, "banana": 30}
stock["apple"] += 20
After update:  {"apple": 70, "banana": 30}

Removing Entries

from collections import Dict

fn main():
    var cart = Dict[String, Int]()
    cart["milk"]   = 2
    cart["bread"]  = 1
    cart["butter"] = 3

    # Customer removes bread from cart
    _ = cart.pop("bread")
    print(len(cart))   # 2

Iterating Over a Dictionary

You can loop through all key-value pairs in a dictionary.

from collections import Dict

fn main():
    var capital = Dict[String, String]()
    capital["France"]  = "Paris"
    capital["Japan"]   = "Tokyo"
    capital["Brazil"]  = "Brasília"

    for entry in capital.items():
        print(entry[].key, "→", entry[].value)

Output (order may vary):

France → Paris
Japan → Tokyo
Brazil → Brasília

Dictionary Size

from collections import Dict

fn main():
    var inventory = Dict[String, Int]()
    inventory["pencil"] = 100
    inventory["pen"]    = 50
    inventory["eraser"] = 75

    print(len(inventory))   # 3

Practical Example: Word Frequency Counter

from collections import Dict

fn main():
    var words = List[String]("mojo", "is", "fast", "mojo", "is", "mojo")
    var freq = Dict[String, Int]()

    for i in range(len(words)):
        var w = words[i]
        if w in freq:
            freq[w] += 1
        else:
            freq[w] = 1

    for entry in freq.items():
        print(entry[].key, ":", entry[].value)

Output (order may vary):

mojo : 3
is   : 2
fast : 1
How it builds:
  "mojo" → {mojo:1}
  "is"   → {mojo:1, is:1}
  "fast" → {mojo:1, is:1, fast:1}
  "mojo" → {mojo:2, is:1, fast:1}
  "is"   → {mojo:2, is:2, fast:1}
  "mojo" → {mojo:3, is:2, fast:1}

Nested Dictionaries

A dictionary can contain other dictionaries as values, enabling hierarchical data representation.

from collections import Dict

fn main():
    var student = Dict[String, String]()
    student["name"]  = "Arjun"
    student["grade"] = "A"
    student["city"]  = "Bangalore"

    print(student["name"], "lives in", student["city"])

Key Takeaways

A dictionary maps unique keys to values. Access values by key name in square brackets. Always check key existence before accessing to avoid runtime errors. Update a value by assigning to an existing key. Use pop() to remove an entry. Iterate with .items() to process all key-value pairs. Dictionaries are ideal for lookups, counters, and grouped data.

Leave a Comment

Your email address will not be published. Required fields are marked *