Julia Working with Dictionaries
Working with a dictionary means checking which keys it holds and reading values safely when a key might be missing. Julia has small functions for each of these jobs.
haskey checks for a key
haskey answers true or false. The key "a" is present below, and "z" is not.
d = Dict("a" => 1, "b" => 2)
println(haskey(d, "a"))
println(haskey(d, "z"))get uses a default for a missing key
get returns the stored value when the key exists. It returns the default instead when the key is missing.
d = Dict("a" => 1, "b" => 2)
println(get(d, "a", 0))
println(get(d, "z", 0))delete! removes a pair
After delete! removes the "a" pair, the count drops to one. A haskey check confirms the key is gone.
d = Dict("a" => 1, "b" => 2)
delete!(d, "a")
println(length(d))
println(haskey(d, "a"))Example
prices = Dict("pear" => 3, "apple" => 2, "fig" => 4)
println(sort(collect(keys(prices))))
println(get(prices, "plum", 0))
delete!(prices, "fig")
println(length(prices))Key points
- haskey: haskey(d, "a") reports whether the key "a" is in the dictionary.
- get: get(d, "z", 0) gives the value for the key, or the default 0 when the key is missing.
- delete!: delete!(d, "a") removes the pair with that key.
- length: length(d) counts the pairs, so it drops by one after a removal.
- keys: keys(d) gives the keys of a dictionary.
- Sorted keys: sort(collect(keys(d))) lists the keys in sorted order.
In this example, the sorted keys print in alphabetical order: apple, fig, pear. The get call then looks up "plum", which is missing, so it prints the default 0. Finally the "fig" pair is deleted, leaving two pairs.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does get(d, "z", 9) return when d = Dict("a" => 1)?