Python - Convert dictionary into list with length based on values
<p>I have a dictionary</p>

<pre><code>d = {1: 3, 5: 6, 10: 2}
</code></pre>

<p>I want to convert it to a list that holds the keys of the dictionary. Each key should be repeated as many times as its associated value.</p>

<p>I've written this code that does the job:</p>

<pre><code>d = {1: 3, 5: 6, 10: 2}
l = []
for i in d:
    for j in range(d[i]):
        l.append(i)
l.sort()
print(l)
</code></pre>

<p>Output:</p>

<pre><code>[1, 1, 1, 5, 5, 5, 5, 5, 5, 10, 10]
</code></pre>

<p>But I would like it to be a list comprehension. How can this be done?</p>

<p><code>[k for k,v in d.items() for _ in range(v)]</code>
... I guess...</p>

<p>if you want it sorted you can do</p>

<p><code>[k for k,v in sorted(d.items()) for _ in range(v)]</code></p>

python list dictionary