When you want to store and look up values based on a unique key, then the dictionary type Dict
(also called hash, associative collection, or map in other languages) is what you need. It is basically a collection of two-element tuples of the form (key, value)
. To define a dictionary d1
as a literal value, the following syntax is used:
// code in Chapter 5\dicts.jl: d1 = Dict(1 => 4.2, 2 => 5.3)
It returns Dict{Int64,Float64}
with two entries: 2 => 5.3
and 1 => 4.2
, so there are two key-value tuples here, (1, 4.2)
and (2, 5.3)
; the key appears before the =>
symbol and the value appears after it, and the tuples are separated by commas.
To explicitly specify the types, use:
d1 = Dict{Int64,Float64}(1 => 4.2, 2 => 5.3)
Note
If you use the former []
notation to try to define a dictionary, you now get Array{Pairs{}}
instead:d1 = [1 => 4.2, 2 => 5.3]
# 2-element Array{Pair{Int64,Float64},1}:
# 1 => 4.2
# 2 => 5.3
Here are some other examples:
d2 = Dict{Any,Any...