getkey

getkey(collection, key, default)

Return the key matching argument key if one exists in collection, otherwise return default.

Examples

In the Julia programming language, the function getkey(collection, key, default)

Return the key matching the argument key if it exists in collection, otherwise return default.

jldoctest
julia> d = Dict("apple" => 1, "banana" => 2, "orange" => 3);
julia> getkey(d, "apple", "Not found")
1

julia> getkey(d, "grape", "Not found")
"Not found"

Here are some common examples of its use:

  1. Get value from a dictionary:

    julia> d = Dict("apple" => 1, "banana" => 2, "orange" => 3);
    julia> getkey(d, "apple", "Not found")
    1

    In this example, the key "apple" exists in the dictionary d, so the corresponding value 1 is returned.

  2. Handle missing key in a dictionary:

    julia> d = Dict("apple" => 1, "banana" => 2, "orange" => 3);
    julia> getkey(d, "grape", "Not found")
    "Not found"

    Here, the key "grape" does not exist in the dictionary d, so the default value "Not found" is returned.

  3. Use with arrays or other collections:
    julia> arr = ["apple", "banana", "orange"];
    julia> getkey(arr, "banana", "Not found")
    "banana"

    In this example, the key "banana" exists in the array arr, so it is returned.

Common mistake example:

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

In this example, the getkey function is called without providing a default value. It's important to always provide the default argument to avoid this error.

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: