Python: Turn List of Tuples into Dictionary of Nested Dictionaries
<p>so I have a bit of an issue on my hands. I have a list of tuples (made up of a level number and message) which will eventually become an HTML list. My issues is that before this happens, I would like to turn the tuples values into a dictionary of nested dictionaries. So here is the example:</p>

<pre><code># I have this list of tuples in format of (level_number, message)
tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]

# And I want to turn it into this
a_dict = {
    'line 1': {
        'line 2': {
            'line 3': {}
        }
    }, 
    'line 4': {}
}
</code></pre>

<p>Any help would be appreciated, as long as it is valid Python 3. Thanks!</p>

<p>Assuming you only have three levels, something like following would do:</p>

<pre><code>tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]

a_dict = {}

for prio, key in tuple_list:
    if prio == 1:
        a_dict[key] = {}
        first_level = key
    if prio == 2:
        a_dict[first_level][key] = {}
        second_level = key
    if prio == 3:
        a_dict[first_level][second_level][key] = {}
    # So on ...
print a_dict
</code></pre>

<p>This also assumes that hierarchies are listed in order, meaning level 1, level 1', level 2, level 3 would be a single dict for level 1, and a hierarchal order like level 1' -> level 2 -> level 3. So the following</p>

<pre><code>tuple_list = [(1, 'line 5'), (1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]
</code></pre>

<p>Would yield the following : </p>

<pre><code>{'line 1': {'line 2': {'line 3': {}}}, 'line 4': {}, 'line 5': {}}
</code></pre>

<p>Or a little more complicated:</p>

<pre><code>tuple_list = [(1, 'line 1'), (2, 'line 2'), (2, 'line 6'), (3, 'line 3'), (3, 'line 7'), (1, 'line 4'), (1, 'line 5')]
</code></pre>

<p>would yield</p>

<pre><code>{'line 1': {'line 2': {}, 'line 6': {'line 3': {}, 'line 7': {}}}, 'line 4': {}, 'line 5': {}}
</code></pre>

<p>Since your levels are not limited to a small number, <strong>it's not a good approach to just do it through plain IFs</strong>. It's better to construct a tree, then traverse the tree and create the representation you want. Doing so is also easy, you have several root nodes (where parent=None), each one has a list of children and this repeats for the children, so you have a tree. You now start from the root and make the ordering you want ! </p>

<p>It's easily implementable and I guess you get the idea !</p>

python list python-3.x dictionary tuples