Wolfram: Association. Check Key Exist

By Xah Lee. Date: . Last updated: .

Check Key Exist

KeyExistsQ[ asso, key ]

return True if the key exist, else False.

xx = Association[ a -> 3,  b -> 2 ];
KeyExistsQ[ xx , b ]
(* True *)

Check Key Exist by Pattern

KeyMemberQ[ asso, pattern]

return True if pattern match any key in asso, else False. 〔see Wolfram: Pattern Syntax

(* check key exist by pattern. string keys example. *)
(* check if any string key match a regex *)

xx = Association[ "a971" -> 3, "b075" -> 2, "c338" -> 5 ]
(* <|a971 -> 3, b075 -> 2, c338 -> 5|> *)

KeyMemberQ[ xx, _?(StringContainsQ[ RegularExpression[ "3+" ] ] ) ]
(* True *)
(* check key exist by pattern. integer keys example. *)
xx = Association[ 31 -> aa, 91 -> bb ];
KeyMemberQ[ xx, _?EvenQ ]
(* False *)
(* check key exist by pattern. expression keys example. *)
(* check if a key has the form f[a,b] where b is integer *)
xx = Association[ aa -> 3, f[3,63] -> 2, f[x,4] -> 31 ];
KeyMemberQ[ xx, f[ _, _Integer ] ]
KeyFreeQ[ asso, pattern]

return True if no key has pattern. 〔see Wolfram: Pattern Syntax

Wolfram. Association (Key Value List)