4
$\begingroup$

I am trying to create an indexed list with Association[] but i getting only a few keys when accesing a specific key. Here is the code:

In[] :=series = Association[
      "white" -> 1,
      "white" -> 0,
      "blue" -> 2,
      "green" -> 1,
      "green" -> 2,
      "yellow" -> 3
      ]
 Out[] :=<|"white" -> 0, "blue" -> 2, "green" -> 2, "yellow" -> 3|>

And when I access the key "white" it only displays number 0, intead of 1 and 0.

 In[]:= series["white"]
 Out:= 0
$\endgroup$

2 Answers 2

6
$\begingroup$

It needs to be done something like the following

Merge[Association /@ {"white" -> 1, "white" -> 0, "blue" -> 2, 
   "green" -> 1, "green" -> 2, "yellow" -> 3}, Join]
%["white"]

{1, 0}

$\endgroup$
2
$\begingroup$

It must be noted that Suba has a great approach, and shows the proper usage of Merge in their answer.

However, if can you make the Association applied to a List, or use a List in any way, there are approaches that I consider to be much simpler which I will show below.

Let's start with the messier version:


Extract[Transpose@{Range@Length@#}][#]&@Inactivate@Association["white" -> 1,
      "white" -> 0,
      "blue" -> 2,
      "green" -> 1,
      "green" -> 2,
      "yellow" -> 3]//GroupBy[#,Extract[1]->Extract[2]]&


(* <|"white" -> {1, 0}, "blue" -> {2}, "green" -> {1, 2}, 
 "yellow" -> {3}|> *)

However, the syntax begins to simplify if there is a list contained within the Association:


Extract[{1,1}]@Defer@Association[{"white" -> 1,
      "white" -> 0,
      "blue" -> 2,
      "green" -> 1,
      "green" -> 2,
      "yellow" -> 3}]//GroupBy[#,Extract[1]->Extract[2]]&


(* same as above *)

Finally, we can realize the cleanest looking implementation of this method, if we are able to use a List of the Associations:


GroupBy[
      {"white" -> 1,
      "white" -> 0,
      "blue" -> 2,
      "green" -> 1,
      "green" -> 2,
      "yellow" -> 3},Extract[1]->Extract[2]]


(* same as above *)

I hope this explains a possible set of alternatives. If you already defined series and wish to use that, unfortunately I cannot currently find a good workaround for that.

Please, let me know if you have any questions!

$\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.