I am attempting to add a key-value pair to a list of associations, but am having trouble.

Minimal Example: Given the list {<| a->1 |>, <| a->2 |>} I would like to add a 'b' key to each association resulting in the final list {<| a->1, b->1 |>, <| a->2, b->2 |>}. With the a and b values not necessarily equal within an association.

I have attempted this using MapThread

MapThread[AssociateTo, {{<|"a" -> 1|>, <|"a" -> 2|>}, {"b" -> 0, "b" -> 1}} ]

But receive the error AssociateTo::rvalue: <|a->1|> is not a variable with a value, so its value cannot be changed.

Any help would be greatly appreciated.

Bonus: Ultimately I would like the 'b' value to be a function of the 'a' value -- E.g. b -> a^2 + 3.


Edit: I have solved the issue using Table

Table[AssociateTo[assoc, "b" -> Function[assoc["a"]^2 + 3] ], {assoc, assocList} ]

But would still like to know why MapThreadgives an error out of curiosity.

  • $\begingroup$ Use Append instead of AssociateTo. Use something like MapThread[Append, {assocs, f /@ assocs}] where f is a function that takes an association and generates a rule b -> value corresponding to that association. $\endgroup$ – C. E. Mar 25 '17 at 19:41

Use Append or Association instead of AssociateTo.

MapThread[Append, {{<|"a" -> 1|>, <|"a" -> 2|>}, {"b" -> 0, "b" -> 1}}]

AssociateTo is the analogue of AppendTo: its argument must be a variable that it will modify. Append (and Association) do not modify their argument. Instead they return a new value.

| improve this answer | |
  • 1
    $\begingroup$ I am puzzled. What does AssociateTo do that AppendTo does not? And if there is differentiating functionality, then why offer AssociateTo as an analog of AppendTo but not Associate as an analog of Append? $\endgroup$ – Alan Sep 7 '17 at 22:44
  • 1
    $\begingroup$ @Alan I was confused about this too until recently. AssociateTo is to Association as AppendTo is to Append. As for the difference, compare Append[<|"a" -> 1, "b" -> 2|>, "a" -> 3] and Association[<|"a" -> 1, "b" -> 2|>, "a" -> 3]. Key ordering will be different. (There are of course other differences, but those are easy to see and boring to talk about: like AssociateTo/Association also taking a list of keys as second arguments.) $\endgroup$ – Szabolcs Sep 7 '17 at 22:47
  • $\begingroup$ Should I be able to cull from the Association docs this usage (first argument an association, followed by the updates, which may include associations)? $\endgroup$ – Alan Sep 7 '17 at 23:05
  • $\begingroup$ @Alan I don't know. There's a feedback link at the bottom of every online doc page ... $\endgroup$ – Szabolcs Sep 7 '17 at 23:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.