Maps in Julia
To create an empty map, use the Dict
constructor:
m = Dict{String, Int}()
Set key/value pairs using typical name[key] = val
syntax.
m["k1"] = 7
m["k2"] = 13
Printing a map using println
will show all of its key/value pairs.
println("map:", m)
Get a value for a key with name[key]
.
v1 = m["k1"]
println("v1:", v1)
If the key doesn’t exist, trying to access it will result in a KeyError
. You can avoid this by using the get
function.
v3 = get(m, "k3", 0)
println("v3:", v3)
The length
function returns the number of key/value pairs in the map.
println("len:", length(m))
Use the delete!
function to remove key/value pairs from a map.
delete!(m, "k2")
println("map:", m)
Clear all key/value pairs from the map using the empty!
function.
empty!(m)
println("map:", m)
Use the haskey
function to check if a key is present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0
or an empty string.
prs = haskey(m, "k2")
println("prs:", prs)
You can also declare and initialize a new map in the same line with this syntax.
n = Dict("foo" => 1, "bar" => 2)
println("map:", n)
Note that maps appear in the form Dict(k => v, k => v)
when printed with println
.
$ julia maps.jl
map: Dict("k1" => 7, "k2" => 13)
v1: 7
v3: 0
len: 2
map: Dict("k1" => 7)
map: Dict()
prs: false
map: Dict("bar" => 2, "foo" => 1)
n == n2
Next example: Functions