delete!

delete!(collection, key)

Delete the mapping for the given key in a collection, and return the collection.

Examples

In the Julia programming language, the function delete!(collection, key)

Delete the mapping for the given key in a collection, and return the modified collection.

jldoctest
julia> d = Dict("apple" => 1, "banana" => 2, "orange" => 3);
julia> delete!(d, "banana")
Dict{String,Int64} with 2 entries:
  "apple"  => 1
  "orange" => 3

Provide common examples of its use. If there are any common mistakes users make, add an example.

  1. Delete a key-value pair from a dictionary:

    julia> d = Dict("apple" => 1, "banana" => 2, "orange" => 3);
    julia> delete!(d, "banana")
    Dict{String,Int64} with 2 entries:
     "apple"  => 1
     "orange" => 3

    In this example, the key "banana" and its corresponding value 2 are removed from the dictionary d.

  2. Modify a dictionary of integers:

    julia> d = Dict(1 => "one", 2 => "two", 3 => "three");
    julia> delete!(d, 2)
    Dict{Int64,String} with 2 entries:
     1 => "one"
     3 => "three"

    It deletes the key 2 and its associated value "two" from the dictionary d.

  3. Handle deleting a non-existent key:
    julia> d = Dict("apple" => 1, "banana" => 2, "orange" => 3);
    julia> delete!(d, "grape")
    Dict{String,Int64} with 3 entries:
     "apple"  => 1
     "banana" => 2
     "orange" => 3

    When attempting to delete a key that doesn't exist in the dictionary, delete! returns the original dictionary without any changes.

Common mistake example:

julia> d = Dict("apple" => 1, "banana" => 2, "orange" => 3);
julia> delete!(d, 2)
ERROR: MethodError: no method matching delete!(::Dict{String,Int64}, ::Int64)

In this example, the key provided is of the wrong type (Int64) instead of String. Make sure to use the correct key type matching the dictionary when using delete!.

See Also

append!, delete!, deleteat!, empty!, endof, filter, filter!, gc, get!, getkey, haskey, insert!, isempty, keys, map, map!, merge, merge!, pop!, prepend!, push!, reduce, resize!, shift!, splice!, unshift!, values,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: