How to add multiple values to a key in a Python dictionary
<p>I am trying to create a dictionary from the values in the <code>name_num</code> dictionary where the length of the list is the new key and the <code>name_num</code> dictionary key and value are the value. So:</p>

<pre><code>name_num = {"Bill": [1,2,3,4], "Bob":[3,4,2], "Mary": [5, 1], "Jim":[6,17,4], "Kim": [21,54,35]}
</code></pre>

<p>I want to create the following dictionary:</p>

<pre><code>new_dict = {4:{"Bill": [1,2,3,4]}, 3:{"Bob":[3,4,2], "Jim":[6,17,4], "Kim": [21,54,35]}, 2:{"Mary": [5, 1]}}
</code></pre>

<p>I've tried many variations, but this code gets me the closest:</p>

<pre><code>for mykey in name_num:
    new_dict[len(name_num[mykey])] = {mykey: name_num[mykey]}
</code></pre>

<p>Output:</p>

<pre><code>new_dict = {4:{"Bill": [1,2,3,4]}, 3:{"Jim":[6,17,4]}, 2:{"Mary": [5, 1]}}
</code></pre>

<p>I know I need to loop through the code somehow so I can add the other values to key 3.</p>

<p>Just an alternative to others; you can sort by length and use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p>

<pre><code>&gt;&gt;&gt; result = {}
&gt;&gt;&gt; f = lambda t: len(t[1])
&gt;&gt;&gt; for length, groups in itertools.groupby(sorted(name_num.items(), key=f), key=f):
...     result[length] = dict((k, v) for k, v in groups)
&gt;&gt;&gt; print result
{
    2: {'Mary': [5, 1]},
    3: {'Bob': [3, 4, 2], 'Jim': [6, 17, 4], 'Kim': [21, 54, 35]},
    4: {'Bill': [1, 2, 3, 4]}
}
</code></pre>

<p>In a worst case scenario where each inner list has a different length, this performs <code>O(n^2)</code> which is fairly inefficient compared to other solutions posted above.</p>

python dictionary