How to update values in an Association using a pattern?

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!

=================

  

 

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.
– Szabolcs
Nov 12 ’15 at 8:42

  

 

What’s the solution to avoid that behavior?
– SuTron
Nov 12 ’15 at 8:46

1

 

There is something wrong in the last output of your post (what is “e” … ?). You probably copied/pasted the wrong example.
– SquareOne
Nov 12 ’15 at 9:23

=================

2 Answers
2

=================

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|>

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|>