haskey
haskey(collection, key) -> Bool
Determine whether a collection has a mapping for a given key.
Examples
julia> dict = Dict(["one"=> 1, "two"=> 2, "three"=> 3])
haskey(dict, "one")
true
julia> dict = Dict(["one"=> 1, "two"=> 2, "three"=> 3])
haskey(dict, "1")
false
julia> dict = ["A"=>1, "B"=>2];
julia> haskey(dict, "A")
true
julia> haskey(dict, 1)
false
-
Check if a dictionary has a specific key:
julia> dict = Dict("apple" => 1, "banana" => 2, "orange" => 3); julia> haskey(dict, "banana") trueThis example checks if the dictionary
dicthas the key"banana". -
Verify if a tuple has a specific element:
julia> tuple = ("apple", "banana", "orange"); julia> haskey(tuple, "orange") trueIt checks if the tuple
tuplecontains the element"orange". - Handle cases where the key is not present:
julia> dict = Dict("apple" => 1, "banana" => 2, "orange" => 3); julia> haskey(dict, "grape") falseThis example demonstrates that
haskeyreturnsfalseif the key is not present in the dictionary.
Common mistake example:
julia> dict = Dict("apple" => 1, "banana" => 2, "orange" => 3);
julia> haskey(dict, 2)
ERROR: MethodError: no method matching haskey(::Dict{String, Int64}, ::Int64)
In this example, the key provided is of a different type (Int64) than the keys in the dictionary (String). It's important to provide the correct key type to haskey to avoid such errors. Make sure the key type matches the key types in the collection.
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.