3
$\begingroup$

Say, having an association:

asc = <|"a" -> 5, "b" -> 4, "c" -> 21|>

I can updated values like:

In[1]:= AssociateTo[asc, {"a" -> 1, "b" -> 2, "c" -> 3}]

Out[1]= <|"a" -> 1, "b" -> 2, "c" -> 3|>

When trying to do that within a list, like:

AssociateTo[asc, {# -> 1}] & /@ {"a", "b", "c"}

I get the association multiplied by the keys count I try to update (1 update per iteration):

{<|"a" -> 1|>, <|"a" -> 1, "b" -> 1|>, <|a" -> 1, "b" -> 1, "c" -> 1|>}

What is wrong here?

Thanks!

$\endgroup$
  • $\begingroup$ AssociateTo will both permanently change its argument (which is unusual among Mathematica functions) and return the new value. Your Map line will both permanently change asc, but it will also return the result of each functions application in a list, as Map normally would. $\endgroup$ – Szabolcs Nov 12 '15 at 8:42
  • $\begingroup$ What's the solution to avoid that behavior? $\endgroup$ – SuTron Nov 12 '15 at 8:46
  • 1
    $\begingroup$ There is something wrong in the last output of your post (what is "e" ... ?). You probably copied/pasted the wrong example. $\endgroup$ – SquareOne Nov 12 '15 at 9:23
6
$\begingroup$

You have applied Mapping wrongly. What you need is:

In[8]:= AssociateTo[asc, # -> 1 & /@ {"a", "b", "c"}]

Out[8]= <|"a" -> 1, "b" -> 1, "c" -> 1|>
$\endgroup$
3
$\begingroup$

You can also use Part [[...]] on Association as you would on any expression:

asc = <|"a" -> 5, "b" -> 4, "c" -> 21|>;

asc[[{"a", "b", "xyz"}]] = 1;

asc

<|a->1,b->1,c->21,xyz->1|>

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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