WolframLang: Association: Filter

By Xah Lee. Date: . Last updated: .

Truncate Association

Take[ assoc, n ]
take first n items. Take
xx = Association[ a -> 1, b -> 2, c -> 3, d -> 4 ];

Take[ xx, 2 ] === <|a -> 1, b -> 2|>

Filter by List of Keys

KeyTake[assoc, {key1, key2 etc}]
return an association containing only the elements with give keys. KeyTake
xx = Association[ a -> 1, b -> 2, c -> 3, d -> 4 ];

KeyTake[ xx, {a, c} ] === <|a -> 1, c -> 3|>
KeyTake[{assoc1, assoc2 etc}, keys]
gives a list of associations.

Filter by Function on Value

Select[ assoc, f]
filter assoc by function f applied to values that return true. Select
xx = Association[ a -> 1, b -> 2, c -> 3, d -> 4 ];

Select[ xx, EvenQ ] === <|b -> 2, d -> 4|>

Filter by Function on Key

KeySelect[assoc, crit]
return a new assoc such that Function crit return True on keys. KeySelect
xx = Association[ 1 -> a, 2 -> b, 3 -> c, 4 -> d ];

KeySelect[ xx, EvenQ ] === <|2 -> b, 4 -> d|>

KeySelect[ xx, Function[ x, Mod[x,3] === 0 ] ] === <|3 -> c|>

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