辞書

2026年3月24日
1 分

辞書の型はキーと値に関する2つの型パラメータを持つ Dict{K, V} で、 Dict{String, Int}() のように初期化する。

julia> d = Dict{String, Int}()
Dict{String, Int64}()

使い方の例を示そう。

julia> d["andy"] = 32
32

julia> d["bill"] = 27
27

julia> d
Dict{String, Int64} with 2 entries:
  "andy" => 32
  "bill" => 27

julia> d["andy"] = 33
33

julia> d["andy"]
33

存在しないキーを指定するとエラーになる。

julia> d["charlie"]
ERROR: KeyError: key "charlie" not found
Stacktrace:
 [1] getindex(h::Dict{String, Int64}, key::String)
   @ Base .\dict.jl:477
 [2] top-level scope
   @ REPL[21]:1

キーが存在するかどうかを確認するには haskey 関数が使える。

julia> haskey(d, "bill")
true

julia> haskey(d, "charlie")
false

他にもいろいろ。