I experienced a problem in changing values in an association and broke down the problem to the following: Given a list of association (here with one element):

temp = {<|"name" -> "Peter", "Punkte" -> 10, "Gender" -> "nn"|>}

then the following does not work:

temp[[1]]["Gender"] = "M"


assoc = temp[[1]]


assoc["Gender"] = "M"

works fine. I do not understand why?

  • $\begingroup$ I have covered exactly this case in this answer, towards the end of the section named "Complications". What works is temp[[1]][[Key["Gender"]]] = "M" (apart from suggestions from other answers, but I believe my suggestion is closer to your original attempt). $\endgroup$ Jan 29 '15 at 13:07

When you try temp[[1]]["Gender"] = "M" you get a warning message:

Association::setps: <|name->Peter,Punkte->10,Gender->nn|> in the part assignment is not a symbol. >>

This is telling you that the syntax assoc[key] = value is only valid if assoc is a symbol. You get the same warning if you try <|a -> 1|>[a] = 2

The simplest solution is to use the Part syntax for changing the value:

temp[[1, "Gender"]] = "M"
(* "M" *)

(* {<|"name" -> "Peter", "Punkte" -> 10, "Gender" -> "M"|>}

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.