Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a dictionary has some key?

Tags:

julia

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?

like image 316
David Varela Avatar asked Jan 10 '20 04:01

David Varela


People also ask

How do you check if a dictionary contains a certain 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.

How do I know if a key isn't in the dictionary?

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.

How do you check a key is exists in dictionary or not with out through KeyError?

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.


2 Answers

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
like image 127
David Varela Avatar answered Oct 23 '22 19:10

David Varela


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.

like image 29
phipsgabler Avatar answered Oct 23 '22 18:10

phipsgabler