WolframLang: Association, Check Key Exist

By Xah Lee. Date: . Last updated: .

Check Key Exist

KeyExistsQ[ asso, key ]

return True if the key exist, else False.

KeyExistsQ

KeyExistsQ[ Association[ a -> 3,  b -> 2 ], b ]

Check Key Exist by Pattern

KeyMemberQ[ asso, pattern]

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

KeyMemberQ

(* check key exist by pattern.
symbol keys example.
 *)

xx = Association[ a -> 3, b -> 2 ];
KeyMemberQ[ xx, _Integer ] === False
(* no keys are integer *)

yy = Association[ a -> 3, 2 -> b ];
KeyMemberQ[ yy, _Integer ] === True
(* some keys are integer *)
(* check key exist by pattern.
integer keys example.
 *)

xx = Association[
311 -> 8,
161 -> 2,
972 -> 9,
91 -> 3
];

(* check if there's key 91 *)
KeyMemberQ[ xx, 91 ] === True

(* check if there's a even number key *)
KeyMemberQ[ xx, _?EvenQ ] === True
(* check key exist by pattern.
string keys example.
 *)

xx = Association[
"a971" -> 3,
"b075" -> 2,
"c338" -> 5,
"d375" -> 0
];

(* check if any string key contains 33 *)
KeyMemberQ[ xx, _?(StringContainsQ[ RegularExpression[ "33" ] ] ) ] === True
KeyFreeQ[ asso, pattern]

opposite of KeyMemberQ

KeyFreeQ

Check Value Exist by Pattern

MemberQ[asso, pattern]

check value exist by Pattern. Return True if pattern matches a value.

(* check value exist by pattern *)

xx = Association[ a -> 3, b -> 2 ];

MemberQ[ xx, 3 ] === True
MemberQ[ xx, _Integer ] === True

MemberQ[ yy, 9 ] === False
xx = Association[ a -> {9, 1}, b -> { 3, 6} ];

(* check if there's a value that's list of pairs with second part a even number *)
MemberQ[ xx, {_, _?EvenQ} ]

WolframLang, Association (Key Value List)