julia - 如何从字典中删除键?

标签 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"

但我想更新现有的字典。我怎样才能在 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/

相关文章:

format - 如何在 IJulia 中选择数字输出格式?

polymorphism - 从抽象类型访问字段时,julia 类型不稳定

Julia 情节.jl : changing marker colour from series recipe

julia - 有没有办法在 Julia 中反转元组的顺序?

julia - 未能报告太小的数字

python - 将数据帧从 python 传输到 julia

julia - 可用作宏中运算符的 ASCII 字符序列

julia - Julia 中缺少、无、未定义和 NaN 之间的用法和约定差异

matrix - 在 Julia 中构造随机正交矩阵序列

dataframe - Julia 中的矢量化 "in"函数?