Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a key from a dictionary?

Tags:

julia

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?

like image 910
David Varela Avatar asked Jan 17 '20 05:01

David Varela


People also ask

How do I remove a key from a list in Python?

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.

How do I remove a key from a list?

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.


1 Answers

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"
like image 79
David Varela Avatar answered Oct 16 '22 10:10

David Varela