Julia Dictionaries
A dictionary is a collection that stores pairs, where each pair links a key to a value. You look a value up by its key instead of by its position.
Build a dictionary and look values up
Each pair joins a key to a value with =>. The key in square brackets gives back its value.
d = Dict("a" => 1, "b" => 2)
println(d["a"])
println(d["b"])Add a pair and change a value
Assigning to a new key adds a pair. Assigning to an existing key replaces its value.
d = Dict("a" => 1)
d["b"] = 5
println(d["b"])
d["a"] = 9
println(d["a"])length counts the pairs
The dictionary below starts with three pairs. Adding one more pair makes the count four.
d = Dict("a" => 1, "b" => 2, "c" => 3)
println(length(d))
d["d"] = 4
println(length(d))Example
scores = Dict("Ana" => 10, "Ben" => 7)
println(scores["Ana"])
scores["Ben"] = 8
scores["Cid"] = 5
println(scores["Ben"])
println(length(scores))Key points
- Pair: a key linked to a value, written with => between them.
- Dict: the function that builds a dictionary from pairs.
- Lookup: writing d["a"] gives the value stored under the key "a".
- Assign: writing d["c"] = 3 adds a new pair, or changes the value when the key already exists.
- length: length(d) counts how many pairs the dictionary holds.
In this example, the dictionary starts with scores for Ana and Ben, and the first lookup prints Ana's 10. Ben's value is then changed to 8, and a new pair for Cid is added. The last two lines print Ben's new value and the total of three pairs.
Note
an array finds items by position, while a dictionary finds values by key.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does println(d["b"]) print after d = Dict("a" => 1, "b" => 2)?