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>Naive solution:</p>

<pre><code>my_dict = {
            ((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
        }

def get_formatted_dict(my_dict):
    formatted_dict = {}
    for k, v in my_dict.items():
        index_1, index_2 = k
        if index_1 not in formatted_dict:
            formatted_dict[index_1] = {}
        formatted_dict[index_1][index_2] = v
    return formatted_dict

print(get_formatted_dict(my_dict))
</code></pre>

<p>Output:</p>

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

python dictionary nested tuples list-comprehension