December 2018
Beginner to intermediate
500 pages
12h 10m
English
As we've already seen, we can index into a Dict using the square bracket notation:
julia> d = Dict(:foo => 1, :bar => 2)
Dict{Symbol,Int64} with 2 entries:
:bar => 2
:foo => 1 julia> d[:bar] 2
Attempting to access a key that has not been defined will result in a KeyError, as follows:
julia> d[:baz] ERROR: KeyError: key :baz not found
To avoid such situations, we can check if the key exists in the first place:
julia> haskey(d, :baz) false
As an alternative, if we want to also get a default value when the key does not exist, we can use the following:
julia> get(d, :baz, 0) 0
The get function has a more powerful twin, get!, which also stores the searched key into the Dict, using the default value:
julia> d Dict{Symbol,Int64} ...Read now
Unlock full access