Dictionaries
Dict[K, V] stores insertion-ordered key-value pairs.
Creating a Dict
Dict[K, V] maps keys to values. Use {} or key-value literals to create dictionaries; update operations return new dictionaries.
scores: Dict[String, Int] = {"Ada" => 98, "Grace" => 100}
-- scores.get_or("Ada", 0) == 98
-- scores.get_or("Grace", 0) == 100
-- scores.length() == 2
Lookup As Option
Dict.get returns Some(value) or None.
scores: Dict[String, Int] = {"Ada" => 98}
func main(args: List[String]) -> Void:
match scores.get("Ada"):
Some(score): print(score) -- prints: 98
None: print("missing")
match scores.get("Lin"):
Some(score): print(score)
None: print("missing") -- prints: missing
Counting
Use get_or to read a previous count before writing the next one.
pure func count_words(words: List[String]) -> Dict[String, Int]:
var result: Dict[String, Int] = {}
for word in words:
result = result.set(word, result.get_or(word, 0) + 1)
result
func main(args: List[String]) -> Void:
counts: Dict[String, Int] = count_words("one two one".words())
-- counts.get_or("one", 0) == 2
-- counts.get_or("two", 0) == 1
-- counts.get_or("missing", 0) == 0
Grouping
Dictionaries are the natural shape for grouping derived values.
pure func group_by_length(names: List[String]) -> Dict[Int, List[String]]:
var result: Dict[Int, List[String]] = {}
for name in names:
length: Int = name.length()
names_for_length: List[String] = result.get_or(length, [])
result = result.set(length, names_for_length.append(name))
result
func main(args: List[String]) -> Void:
groups: Dict[Int, List[String]] = group_by_length(["Ada", "Grace", "Alan"])
-- groups.get_or(3, []) == ["Ada"]
-- groups.get_or(4, []) == ["Alan"]
-- groups.get_or(5, []) == ["Grace"]
Insertion Order
Dict iteration follows insertion order.
scores: Dict[String, Int] = {"Ada" => 98, "Grace" => 100}
func main(args: List[String]) -> Void:
for (name, score) in scores:
print(name) -- prints: Ada, then Grace
Example
word-count.brp
pure func count_words(words: List[String]) -> Dict[String, Int]:
var counts: Dict[String, Int] = {}
for word in words:
counts = counts.set(word, counts.get_or(word, 0) + 1)
counts
func main(args: List[String]) -> Void:
counts: Dict[String, Int] = count_words("one two one".words())
print(counts.get_or("one", 0)) -- prints: 2
print(counts.get_or("two", 0)) -- prints: 1
print(counts.keys().join(", ")) -- prints: one, two
Try it
terminal
blorp run examples/docs/core-data/dictionaries/word-count.brp