# What is this Counts[] output format?

I need to create a list of the distinct elements in a list along with the number of times each appears.

The function Counts[] is supposed to do this, but it puts the results in some weird format I've never seen before and don't know how to use.

nn = RandomInteger[5, 200];
Counts[Sort[nn]];

(* <|0 -> 36, 1 -> 30, 2 -> 31, 3 -> 33, 4 -> 36, 5 -> 34|> *)


And OF COURSE the online-documentation on Counts[] doesn't cover this topic AT ALL (grumble, grumble)...

So, I hacked my own function to do the counts and put them in a nice array:

a = Gather[Sort[nn]];
Table[{a[[i, 1]], Length[a[[i]]]}, {i, 1, Length[a]}]

(* {{0, 36}, {1, 30}, {2, 31}, {3, 33}, {4, 36}, {5, 34}} *)


But what is that output format that Counts[] returns? How can I access the numbers in it?

• That is a pretty useful type introduced in MMA 10, Association. check it out, you will like it. – Kattern Jun 6 '15 at 7:43
• You can also use Tally e.g. Tally[Sort@nn] – ubpdqn Jun 6 '15 at 7:54
• The documentation for Counts says (in the Details section) "Counts[list] gives an association whose keys are in the same order as they first occur as elements of list.", so you then look up Association and all is revealed. However, I agree with you that the documentation could be improved, e.g. Wolfram should add an explicit link to Association. – Stephen Luttrell Jun 6 '15 at 10:34
• @StephenLuttrell Ah. Yes, I saw that, but I didn't realize that by "association" they were referring to a specific data structure. – Jerry Guern Jun 6 '15 at 19:52

This is a very connivent function introduced in Mathematica v10. The old solution of hash table is presented at: How to get the list of defined values for an indexed variable? Now you can do it with Association pretty easy.
nn = RandomInteger[5, 200];