我想从字典中删除一个键值对。
我现在正在创建一个新字典:
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"
但我想更新现有的字典。我怎样才能在 Julia 中做到这一点?
最佳答案
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"
使用
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
您可以避免使用
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)
使用
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"
关于julia - 如何从字典中删除键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59781733/