如何从字典中删除键?

Dav*_*ela 8 julia

我想从字典中删除一个键值对。

我现在正在创建一个新字典:

julia> dict = Dict(1 => "one", 2 => "two")
Dict{Int64,String} with 2 entries:
  2 => "two"
  1 => "one"

julia> dict = Dict(k => v for (k, v) in dict if k != 2)
Dict{Int64,String} with 1 entry:
  1 => "one"
Run Code Online (Sandbox Code Playgroud)

但我想更新现有的字典。我怎样才能在 Julia 中做到这一点?

Dav*_*ela 12

delete!如果键存在,将从字典中删除键值对,如果键不存在则无效。它返回对字典的引用:

julia> dict = Dict(1 => "one", 2 => "two")
Dict{Int64,String} with 2 entries:
  2 => "two"
  1 => "one"

julia> delete!(dict, 1)
Dict{Int64,String} with 1 entry:
  2 => "two"
Run Code Online (Sandbox Code Playgroud)

使用pop!如果需要使用与键关联的值。但是如果key不存在就会报错:

julia> dict = Dict(1 => "one", 2 => "two");

julia> value = pop!(dict, 2)
"two"

julia> dict
Dict{Int64,String} with 1 entry:
  1 => "one"

julia> value = pop!(dict, 2)
ERROR: KeyError: key 2 not found
Run Code Online (Sandbox Code Playgroud)

您可以避免使用三个参数版本的pop!. 第三个参数是在键不存在的情况下返回的默认值:

julia> dict = Dict(1 => "one", 2 => "two");

julia> value_or_default = pop!(dict, 2, nothing)
"two"

julia> dict
Dict{Int64,String} with 1 entry:
  1 => "one"

julia> value_or_default = pop!(dict, 2, nothing)
Run Code Online (Sandbox Code Playgroud)

用于filter!根据某些谓词函数批量删除键值对:

julia> dict = Dict(1 => "one", 2 => "two", 3 => "three", 4 => "four");

julia> filter!(p -> iseven(p.first), dict)
Dict{Int64,String} with 2 entries:
  4 => "four"
  2 => "two"
Run Code Online (Sandbox Code Playgroud)