Creating nested dict from dict with nested tuples as keys using comprehension
<p>I got a very useful answer for this problem here earlier this year, but there I could use pandas. Now I have to do it with pure Python.</p>

<p>There is a dict like this:</p>

<pre><code>inp = {((0, 0), 0): -99.94360791266038,
       ((0, 0), 1): -1.1111111111107184,
       ((1, 0), 0): -1.111111111107987,
       ((1, 0), 1): -1.1111111111079839,
       ((1, 0), 3): -1.111111111108079}
</code></pre>

<p>Now I want to convert this in a nested dict like this:</p>

<pre><code>out = {(0,0): {0: -99.94360791266038, 1: -1.1111111111107184},
       (1,0): {0: -1.111111111107987,
               1: -1.1111111111079839,
               3: -1.111111111108079}
</code></pre>

<p>How can I do this with an elegant diction comprehension? I just can't get my head around it.</p>

<p>I'd not do this with a dict comprenhesion. Just use a simple loop:</p>

<pre><code>out = {}
for key, value in inp.items():
    k1, k2 = key
    out.setdefault(k1, {})[k2] = value
</code></pre>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; inp = {((0, 0), 0): -99.94360791266038,
...        ((0, 0), 1): -1.1111111111107184,
...        ((1, 0), 0): -1.111111111107987,
...        ((1, 0), 1): -1.1111111111079839,
...        ((1, 0), 3): -1.111111111108079}
&gt;&gt;&gt; out = {}
&gt;&gt;&gt; for key, value in inp.items():
...     k1, k2 = key
...     out.setdefault(k1, {})[k2] = value
...
&gt;&gt;&gt; from pprint import pprint
&gt;&gt;&gt; pprint(out)
{(0, 0): {0: -99.94360791266038, 1: -1.1111111111107184},
 (1, 0): {0: -1.111111111107987,
          1: -1.1111111111079839,
          3: -1.111111111108079}}
</code></pre>

<p>To do the same with a dict comprehension is possible, but you need to then sort the keys and use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a> to group the keys on on the first tuple element. The sorting takes O(NlogN) time, and a simple loop like the above beats that easily.</p>

<p>Still, for completeness sake:</p>

<pre><code>from itertools import groupby
out = {g: {k[1]: v for k, v in items} 
       for g, items in groupby(sorted(inp.items()), key=lambda kv: kv[0][0])}
</code></pre>

python dictionary nested tuples list-comprehension