Skip to main content
2 of 5
Formatted code
Michael E2
  • 244.8k
  • 18
  • 351
  • 774

Changing Values in an Association using Map

I am trying to change the value of one key in an association based on the value of another key in that association. So if my association starts as:

x=<|"firstValue" -> True, "isFirstValueTrue" -> False|>

I want to change it to:

<|"firstValue" -> True, "isFirstValueTrue" -> True|>

So I wrote the function:

f[x_] := If[x[["firstValue"]], x[["isFirstValueTrue"]] = True, x[["isFirstValueTrue"]] = False]

I got an error, but based on this answer: http://stackoverflow.com/questions/12875913/setsetps-in-the-part-assignment-is-not-a-symbol I was to correct it by using:

SetAttributes[f, HoldAll].

But let's say I want to do this to a list of associations:

    x={<|"firstValue" -> True, "isFirstValueTrue" -> False|>,
     <|"firstValue" -> True, "isFirstValueTrue" -> True|>,
     <|"firstValue" -> False, "isFirstValueTrue" -> False|>,
     <|"firstValue" -> False, "isFirstValueTrue" -> True|>}

so I wrote:

Map[f[#] &, x]

However, the "in the part assignment is not a symbol." error appears again and you can't SetAttributes[Map, HoldAll]. I realize I can make a copy of the list and make changes to that, but the actual list I'm working with is much larger so I do not want to do that. The third solution in the link above is able to be mapped, but it doesn't seem like you can replace in an association. Any suggestions?

Jon F.
  • 645
  • 8
  • 8