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>One approach is to use <a href="https://docs.python.org/3.6/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain</code></a> to glue sublists together</p>

<pre><code>&gt;&gt;&gt; list(itertools.chain(*[[k]*v for k, v in d.items()]))
[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]
</code></pre>

<p>Or if you are dealing with a very large dictionary, then you could avoid constructing the sub lists with <a href="https://docs.python.org/3.6/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a> and <a href="https://docs.python.org/3.6/library/itertools.html#itertools.repeat" rel="nofollow"><code>itertools.repeat</code></a></p>

<pre><code>&gt;&gt;&gt; list(itertools.chain.from_iterable(itertools.repeat(k, v) for k, v in d.items()))
[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]
</code></pre>

<p>Comparative timings for a very large dictionary with using a list comprehension that uses two loops:</p>

<pre><code>&gt;&gt;&gt; d = {i: i for i in range(100)}
&gt;&gt;&gt; %timeit list(itertools.chain.from_iterable(itertools.repeat(k, v) for k, v in d.items()))
10000 loops, best of 3: 55.6 Âµs per loop
&gt;&gt;&gt; %timeit [k for k, v in d.items() for _ in range(v)]
10000 loops, best of 3: 119 Âµs per loop
</code></pre>

<p>It's not clear whether you want your output sorted (your example code does not sort it), but if so simply presort <code>d.items()</code></p>

<pre><code># same as previous examples, but we sort d.items()
list(itertools.chain(*[[k]*v for k, v in sorted(d.items())]))
</code></pre>

python list dictionary