Reputation: 6976
I want to remove a key-value pair from a dictionary.
I am creating a new dictionary for now:
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"
But I want to update the existing dictionary instead. How can I do this in Julia?
Upvotes: 14
Views: 9632
Reputation: 6976
delete!
will remove a key-value pair from a dictionary if the key exists, and have no effect if the key does not exist. It returns a reference to the dictionary:
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"
Use pop!
if you need to use the value associated with the key. However, it will error if the key does not exist:
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
You can avoid throwing an error with the three argument version of pop!
. The third argument is a default value to return in case the key does not exist:
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)
Use filter!
to bulk remove key-value pairs according to some predicate function:
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"
Upvotes: 22