Dictionaries
Last updated:
A Dictionary in Julia is a collection of key-value pairs, which provide much more flexibility than arrays or named tuples. In particular, Dictionaries are mutable, and the keys can be of any type (where in Arrays they have to be Integers, and in Named Tuples, symbols).
Creating a Dictionary
We can create a dictionary using the following syntax:
D = Dict("a" => 1, "b" => 2, 1 => "a")
Alternatively, we can initialize a Dictionary using key/value pairs:
D = Dict([("a", 1), ("b", 2), (1,"a")])
Accessing Elements of a Dictionary
Elements of a dictionary can be accessed similarly to arrays, using the corresponding keys: for example, doing D["a"]
or D[1]
will return the corresponding values of 1
and "a"
.
Dictionaries are also iterable objects, so we can loop through the elements of a given dictionary:
for e in D
println(e)
end
as each element in a dictionary is a Pair, we can access individual components of e
doing e[1]
and e[2]
. More conveniently, we can unstructure the pair into two variables, as follows:
for (k,v) in D
println(k, " => ", v)
end
b => 2
a => 1
1 => a
Modifying a Dictionary
One important characteristics of dictionaries is that they are mutable structures, so can be modified. For example, the following is possible:
D["c"] = 3 # Adding a new key
D["c"] = "Hello" # Updating existing key
D = delete!(D, "c") # Deleting an existing key