3

Saying we have an association:

asc = <|"A" -> <|"a" -> 1, "b" -> 2, "c" -> 3|>|>;

I want to updated values of "A". I have tried doing:

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

<|"A" -> <|"a" -> 1, "b" -> 2, "c" -> 3|>, 1 -> 0, 2 -> 2, 3 -> 3|>

But this just adds valuesst to the association instead of adding to "A"

How can I update the values in "A" using AssociateTo?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
SuTron
  • 1,708
  • 1
  • 11
  • 21

2 Answers2

5

One possibility would be the simple

asc["A"]["a"] = 99;

enter image description here

As @m_goldberg commented this can be shortened to

asc["A", "a"] = 99;

To change several keys:

asc[[1]][[2 ;; 3]] = 4

enter image description here

eldo
  • 67,911
  • 5
  • 60
  • 168
0

I have came up with a solution:

In[1]:= asc = <|"A" -> <|"a" -> 1, "b" -> 2, "c" -> 3|>|>;
Module[{tmp = asc["A"]},
 AssociateTo[tmp, # -> tmp[#] + 1 & /@ {"a"}];
 AssociateTo[asc, "A" -> tmp]
 ]

Out[2]= <|"A" -> <|"a" -> 2, "b" -> 2, "c" -> 3|>|>
SuTron
  • 1,708
  • 1
  • 11
  • 21
  • 1
    Why do you have to use AssocTo? It is a very poor tool for solving your problem. The simple expression asc["A", "a"] = asc["A", "a"] + 1; is much better. – m_goldberg Nov 13 '15 at 16:41
  • The question asks how to do that using AssociateTo[]. For complicated and nested associations it's a better fit to apply changes, when you need to do additional checks on keys. – SuTron Nov 20 '15 at 13:18