如何向现有字典添加新的键值对?

Dav*_*ela 6 julia

我有一些已经存在的字典。我想添加一个新的键值对,但我不想从头开始创建一个新字典。

如何向 Julia 中的现有字典添加新的键值对?

Dav*_*ela 7

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] = valuesetindex!调用的语法。虽然不常见,但你可以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)