WolframLang: Association, Check Key Exist

By Xah Lee. Date: . Last updated: .

Check Key Exist

KeyExistsQ[ assoc, key ]
returns True if the key exist, else False.
KeyExistsQ
KeyExistsQ[ Association[ a -> 3,  b -> 2 ], b ]

Check Key Exist by Pattern

KeyMemberQ[ assoc, pattern]
return True if pattern match any key in assoc, else False. [see WolframLang: Pattern Syntax] KeyMemberQ
(* check key exist by pattern *)

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

yy = Association[ a -> 3, 2 -> b ];
KeyMemberQ[ yy, _Integer ] === True
KeyMemberQ[ assoc, pattern]
opposite of KeyMemberQ KeyFreeQ

Check Value Exist by Pattern

MemberQ[assoc, 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 Pairs)

WolframLang in Depth

Basics

Comment, Print

String

Arithmetic

List

Expression, Atom, Head

Boolean

Conditional

Variable

Loop

Data Structure

Function

Pattern Matching

Advanced

Shell Tasks

Misc