# Opposite of Counts

I would like to reverse the effect of Counts, i.e., starting with

x = <|a -> 4, b -> 2, c -> 1|>


I would like to reconstruct a sorted list

y = {a, a, a, a, b, b, c}


such that Counts[y] == x. I have come up with

y = Join @@ ConstantArray @@@ Normal @ x


but I'd like to know if there's anything more elegant than this, with less intermediary expressions.

• Essentially a duplicate on Stack Overflow: (763915) Commented Apr 26, 2017 at 16:27
• Wow, I would never find that question in search for relateds, @Mr.Wizard. But what I take from your answer there is that the method I'm suggesting is about as good as it gets, right? Commented Apr 26, 2017 at 17:31
• Well, it's what I would use, still; you can take that for what it's worth. :-) Commented Apr 26, 2017 at 19:17

## 3 Answers

Catenate @ KeyValueMap[ConstantArray] @ x


Related topics:

Reverse DeleteDuplicates using Information from Tally

Generating repeated elements in a list

Replicate sublist in new list

List creation/manipulation

• Catenate @ KeyValueMap[Table] @ x ought to work as well. Commented Apr 19, 2017 at 11:16
• @J.M. yep, I think ConstantArray has better performance but I don't remember where to find benchmarks, I just use it by default. p.s. any idea why only the first link is automatically formatted?
– Kuba
Commented Apr 19, 2017 at 11:18
• I changed your links to use https://. Commented Apr 19, 2017 at 11:25
• @Kuba A little and I think we even can ignored it.
– yode
Commented Apr 26, 2017 at 11:28
• @Kuba I believe the key difference is that if it is numeric input, ConstantArray generates packed arrays. But, Catenate doesn't respect packed arrays, so you instead have to use Join @@ KeyValueMap[ConstantArray]@<|1 -> 4, 2 -> 2, 3 -> 1|>, instead. Commented Apr 26, 2017 at 16:23
KeyValueMap[Table /* Apply[Sequence], x]


{a, a, a, a, b, b, c}

Multiplication of Matrices

In:

xs = <|a -> 4, b -> 2, c -> 1|>;
A = Table[1, #] & /@ Values[xs]
B = Keys[xs]
A B // Flatten


Out:

{{1, 1, 1, 1}, {1, 1}, {1}}
{a, b, c}
{a, a, a, a, b, b, c}