isKey
Tests whether keys are present in a containers.Map or dictionary.
Category: Language Fundamentals > Data Types
Syntax
tf = isKey(M, key)
Returns true if key is a key of the map M.
tf = isKey(M, keys)
With a cell array of keys, tests each one and returns a logical array of the same size.
Description
isKey is the safe way to guard a lookup, because reading a missing key with M(key) raises an error. Character keys are compared case-sensitively.
For a containers.Map it is written isKey(M, key); for a dictionary the same function applies and M.isKey(key) is also accepted.
Input arguments
M- A
containers.Mapor adictionaryobject. key, keys- A key, or a cell array of keys. Its type must match the key type of the map.
Output arguments
tf- Logical scalar, or an array the size of the cell array
keys.
Example
Guarding a lookup
m = containers.Map({'a','b'}, [1 2]);
isKey(m, 'a')
isKey(m, {'a','z'})
if isKey(m, 'b'), disp(m('b')), end
Output
ans = logical
1
ans = 1×2 logical array
1 0
2