Python: Reconstruct a list by its element counts

Viewed 178

I had a list with several elements (0,1,2,3,...)

Now I have a dict with above unique elements as keys, their counts as values:

{0:1, 1:3, 2:4, 3:6}

And I want to reconstruct it back to a list

[0, 1,1,1, 2,2,2,2, 3,3,3,3,3,3]

Is there any pythonic way the achieve this? vanilla or with numpy.

3 Answers
from collections import Counter

c = Counter({0:1, 1:3, 2:4, 3:6})

list(c.elements())

You can simply use sum() for this:

d = {0:1, 1:3, 2:4, 3:6}
d = sum([[k]*v for k,v in d.items()], [])

This is a numpy way:

d = {0:1, 1:3, 2:4, 3:6}
np.repeat(list(d.keys()), list(d.values()))
Related