Suppose I have a Dict
object and a key value and I want to see if there's already an entry in the dictionary for that key? How do I do this?
There are a few ways to do this. Suppose this is your dictionary:
d = Dict(
"aardvark" => 1,
"bear" => 2,
"cat" => 3,
"dog" => 4,
)
If you have a key you can check for its presence using the haskey
function:
julia> haskey(d, "cat")
true
julia> haskey(d, "zebra")
false
A slightly fancier way to check this is to check if the key is in the set of keys returned by calling keys(d)
:
julia> ks = keys(d)
Base.KeySet for a Dict{String,Int64} with 4 entries. Keys:
"aardvark"
"bear"
"cat"
"dog"
julia> "cat" in ks
true
julia> "zebra" in ks
false
Finally, it's fairly common that you want to get the value associated with a key if it is present in the dictionary. You can do that as a separate step by doing d[k]
after checking that k
is present in keys(d)
but that involves an additional dictionary lookup. Instead, if there is some sentinel value that you know cannot be a value in your dictionary, such as nothing
, then you can use the get
function to look up the key with a default:
v = get(d, k, nothing)
if v !== nothing
# keys(d) contains k
end
If you know nothing about the kinds of values that d
can map keys to, this is not a safe option since it could be the case that the pair k => nothing
is present in d
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With