Dictionaries
Dictionaries (also called maps or hash maps) store key-value pairs. Keys are strings, and values can be any type.
Creating a dictionary
Use curly braces with string keys and values:
let user = {"name": "Alice", "age": 30};
let config = {"debug": true, "port": 8080};Accessing values
Use bracket notation with a string key:
let user = {"name": "Alice", "age": 30};
print(user["name"]); // "Alice"
print(user["age"]); // 30Adding or updating entries
Assign to a key to add or update:
let user = {"name": "Alice"};
user["age"] = 30; // Add new key
user["name"] = "Bob"; // Update existing key
print(user); // {"name": "Bob", "age": 30}Dictionary length
Use len() to get the number of key-value pairs:
let user = {"a": 1, "b": 2, "c": 3};
print(len(user)); // 3Type annotation
Use the dict type:
let user: dict = {"name": "Alice"};Example: Counting words
class WordCounter {
let words = {"hello": 0, "world": 0};
fn count(word) {
if (word == "hello") {
words["hello"] = words["hello"] + 1;
}
if (word == "world") {
words["world"] = words["world"] + 1;
}
}
fn show() {
print(words);
}
}