Wolfram: Association. Add Item

By Xah Lee. Date: . Last updated: .

Modify Variable In-place, Append Item, via Assignment Syntax

assoVar[key]=val
  • Add a item to assoVar.
  • If the key exists, its value is updated.
  • assoVar must be a variable.
  • The variable is modified.
  • Return val.
xx = Association[]
(* <||> *)

xx["c"] = 4
(* 4 *)

xx
(* <|c -> 4|> *)

Modify Variable In-place, Append Item, via Function

AssociateTo[ assoVar, rule ]
  • Add a rule to a assoc variable assoVar.
  • If the key exists, its value is updated.
  • assoVar must be a variable.
  • The variable is modified.
  • Return the updated assoVar.
xx = Association[]
(* <||> *)

yy = AssociateTo[ xx, {"c" -> 4} ]
(* <|c -> 4|> *)

xx
(* <|c -> 4|> *)

(* the variable is modified *)
xx === yy
(* True *)
(* If the arg is not a variable, nothing is done. *)
AssociateTo[ Association[], {"c" -> 4} ]
(* AssociateTo[Association[], {c -> 4}] *)
AssociateTo[ assoVar, listOfRules]

Add multiple items.

xx = Association[ a -> 1, b -> 2 ];
AssociateTo[ xx, {a -> 33, c -> 88} ]
(* <|a -> 33, b -> 2, c -> 88|> *)

PrependTo

PrependTo[assoVar, newRule]
xx = Association[aa -> 3]
(* <|aa -> 3|> *)

yy = PrependTo[ xx, "c" -> 4 ]
(* <|c -> 4, aa -> 3|> *)

(* the variable is modified *)
xx === yy
(* True *)

AppendTo

AppendTo[assoVar, newRule]

similar to AssociateTo, but is more generally designed for list.

Functions that Return a New Association

Append

Append[asso, newRule]

Prepend

Prepend[asso, newRule]

Insert at a Given Position

Insert[asso, rule, i]
  • Insert rule at position i.
  • If key exist, just update the key's value.
  • Variable not modified
  • Return the new association.
xx = Association[ a -> 1, b -> 2 ]

(* if key exist, update value *)
Insert[ xx, a -> 99, 2 ]
(* <|a -> 99, b -> 2|> *)

(* variable not modified *)
xx
(* <|a -> 1, b -> 2|> *)

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

(* if key no exist, insert at specified index *)
Insert[ xx, c -> 77, 1 ]
(* <|c -> 77, a -> 1, b -> 2|> *)

Wolfram. Association (Key Value List)