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>You can do it using a list comprehension:</p>

<pre><code>[i for i in d for j in range(d[i])]
</code></pre>

<p>yields:</p>

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

<p>You can sort it again to get the list you were looking for.</p>

python list dictionary