Wolfram: Association. Add Item

By Xah Lee. Date: . Last updated: .

Association Variable, Append Item by Assignment Syntax

assoVar[key]=val
  • Add a item to assoVar.
  • If the key exists, its value is updated.
  • assoVar must be a variable.
  • Return val.
xx = Association[ "a" -> 3 ];
xx["c"] = 4
(* 4 *)

xx
(* <|a -> 3, c -> 4|> *)

Association Variable, Append Item

AssociateTo[ assoVar, rule ]
  • Add a rule to a assoc variable assoVar and modify the variable.
  • If the key exists, its value is updated.
  • Return the updated assoVar.

AssociateTo

xx = Association[ "a" -> 3 ];
yy = AssociateTo[ xx, {"c" -> 4} ];

xx
(* <|a -> 3, c -> 4|> *)

xx === yy
(* True *)
AssociateTo[ assoVar, listOfRules]

Add multiple items.

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

Append

Append[asso, newRule]

Append

AppendTo

AppendTo[assoVar, newRule]

AppendTo

Prepend

Prepend[asso, newRule]

Prepend

PrependTo[assoVar, newRule]

PrependTo

Insert at a Given Position

Insert[asso, rule, i]
  • Insert rule at position i.
  • If key exist, just update the key's value.
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|> *)

WolframLang, Association (Key Value List)