get!(collection, key, default)

Return the value stored for the given key, or if no mapping for the key is present, store key => default, and return default.


julia> dict = {"A"=>1, "B"=>2};

julia> get!(dict,"A",42)

julia> get!(dict,"C",42)

julia>  get!(dict,"D") do       # equivalent to get!(() -> 100, dict, "D");
        return 100

julia> dict
Dict{Any,Any} with 4 entries:
 "B" => 2
 "A" => 1
 "C" => 42
 "D" => 100
  1. Retrieve the value for a key from a dictionary:

    julia> dict = Dict("a" => 1, "b" => 2, "c" => 3);
    julia> get!(dict, "b")

    This example retrieves the value associated with the key "b" from the dictionary dict. If the key is present, it returns the value.

  2. Handle missing keys and set a default value using a function:

    julia> dict = Dict("a" => 1, "b" => 2);
    julia> get!(dict, "c", () -> 100)

    In this case, the key "c" is not present in the dictionary. The function () -> 100 is called to generate a default value of 100, store the key-value pair in the dictionary, and return the value.

  3. Use do block syntax with a function to generate default value:
    julia> dict = Dict("a" => 1, "b" => 2);
    julia> get!(dict, "c") do
              # default value calculated here
              "new value"
    "new value"

    This example uses the do block syntax to calculate and return a default value for the missing key "c". The block of code within the do block is executed to generate the default value, store it in the dictionary, and return the value.

Common mistake example:

julia> dict = Dict("a" => 1, "b" => 2);
julia> get!(dict, "b", 10)
ERROR: MethodError: no method matching get!(::Dict{String,Int64}, ::String, ::Int64)

In this example, the third argument is provided as 10, which is not a function. The correct usage is to provide a function as the third argument to generate the default value. Ensure that the third argument is a function when using get!.

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

Checking you are not a robot: