Wolfram: Association. Get Value

By Xah Lee. Date: . Last updated: .

Get Key's Value by Key

Lookup[asso, key]

return the value of key.

If the key is missing, return Missing["KeyAbsent", key]

Lookup

xx = Association[ "a" -> 3, "b" -> 2 ]
(* <|a -> 3, b -> 2|> *)

Lookup[xx, "b"]
(* 2 *)

Lookup[xx, "c"]
(* Missing["KeyAbsent", "c"] *)
Lookup[asso, key, default]

use default if the key missing.

xx = Association[ "a" -> 3, "b" -> 2 ];
Lookup[xx, "c", 99]
(* 99 *)
Lookup[asso, listOfKeys]

Return a list of the values. From list of keys.

Lookup[listOfAssoc, key]

Return a list of values. From the list of associations.

Alternative, Syntactical Form of Get Key's Value by Key

asso[key]

return the value of a key.

If the key is missing, return Missing["KeyAbsent", key]

Missing

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

xx["b"]
(* 2 *)

xx["c"]
(* Missing["KeyAbsent", "c"] *)

Key Representation

Key[expr]

represent a key in a Wolfram: Association (Key Value List)

normally, when you lookup a key, e.g.

Lookup[asso, key]

or

asso[key]

the key is simple, such as a string, number, symbol.

but when asso has complicated expression as key e.g.

Association[ f[x] -> 3, {3,4} -> 2 ]

you need to quote the key by Key[key], e.g.

Lookup[asso, Key[{3,4}]]

xx = Association[ 1 -> 11, "b" -> 22, {3,4} -> 33 ];

xx["b"] === 22
(* True *)

Lookup[xx, "b"] === 22
(* True *)

(* HHHH------------------------------ *)

xx[1] === 11
(* True *)

Lookup[xx, 1] === 11
(* True *)

(* HHHH------------------------------ *)

Lookup[xx, {3,4}]
(* {Missing[KeyAbsent, 3], Missing[KeyAbsent, 4]} *)

Lookup[xx, Key[{3,4}]]
(* 33 *)
Key[expr][asso]

return the value of a key in a asso.

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

Get Key's Value by Index

to get the value by index, just use Part

Part[ Association[ "a" -> 3, "b" -> 2 ], 1 ]
(* 3 *)

(* same as *)

Association[ "a" -> 3, "b" -> 2 ][[1]]
(* 3 *)

WolframLang, Association (Key Value List)