I want to key into a dictionary, but Julia throws an exception if the key does not exist. To avoid the exception, I first have to check if they key exists in the dictionary.
I'm using this custom function for now:
function has_some_key(dict, key)
for (k, v) in dict
if k == key
return true
end
end
return false
end
Is there a better way to determine if a dictionary has a mapping for a given key?
Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
Check if Key Exists using in Operator The simplest way to check if a key exists in a dictionary is to use the in operator. It's a special operator used to evaluate the membership of a value.
python check if key in dictionary using try/except If we try to access the value of key that does not exist in the dictionary, then it will raise KeyError. This can also be a way to check if exist in dict or not i.e. Here it confirms that the key 'test' exist in the dictionary.
haskey
will check whether some collection has a mapping for a given key:
julia> d
Dict{Int64,String} with 2 entries:
2 => "two"
1 => "one"
julia> haskey(d, 1)
true
julia> haskey(d, 3)
false
Another way, which might be viable depending on your use case, is to use get
to provide a default value in case the key is not present:
julia> d = Dict(1 => "one", 2 => "two")
Dict{Int64,String} with 2 entries:
2 => "two"
1 => "one"
julia> get(d, 1, "zero")
"one"
julia> get(d, 3, "zero")
"zero"
There's also get!
, which will store the default value for the queried key as well.
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