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?
In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.
Method #1 : Using loop + del The combination of above functions can be used to solve this problem. In this, we iterate for all the keys and delete the required key from each dictionary using del.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With