Julia 使用通用dict[key] = value语法来设置键值对:
julia> dict = Dict(1 => "one")
Dict{Int64,String} with 1 entry:
1 => "one"
julia> dict[2] = "two"
"two"
julia> dict
Dict{Int64,String} with 2 entries:
2 => "two"
1 => "one"
Run Code Online (Sandbox Code Playgroud)
如果键已经存在,相同的语法将覆盖键值对:
julia> dict
Dict{Int64,String} with 2 entries:
2 => "two"
1 => "one"
julia> dict[1] = "foo"
"foo"
julia> dict
Dict{Int64,String} with 2 entries:
2 => "two"
1 => "foo"
Run Code Online (Sandbox Code Playgroud)
dict[key] = value是setindex!调用的语法。虽然不常见,但你可以setindex!直接调用:
julia> dict = Dict(1 => "one")
Dict{Int64,String} with 1 entry:
1 => "one"
julia> setindex!(dict, "two", 2)
Dict{Int64,String} with 2 entries:
2 => "two"
1 => "one"
Run Code Online (Sandbox Code Playgroud)