我有一些已经存在的字典。我想添加一个新的键值对,但是我不想从头开始创建一个新的字典。
如何在Julia中现有的词典中添加新的键值对?
答案 0 :(得分:5)
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"
如果键已经存在,则相同的语法将覆盖键值对:
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"
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"