Grouping Python dictionaries in hierachical form
<p>I have a list of dictionaries and I wanted to group the data. I used the following:</p>

<pre><code>group_list = []
for key, items in itertools.groupby(res, operator.itemgetter('dept')):
    group_list.append({key:list(items)})
</code></pre>

<p>For data that looks like this </p>

<pre><code>[{'dept':1, 'age':10, 'name':'Sam'},
{'dept':1, 'age':12, 'name':'John'},
.
.
.
{'dept':2,'age':20, 'name':'Mary'},
{'dept':2,'age':11, 'name':'Mark'},
{'dept':2,'age':11, 'name':'Tom'}]
</code></pre>

<p>the output would be:</p>

<pre><code>[{1:[{'dept':1, 'age':10, 'name':'Sam'},
    {'dept':1, 'age':12, 'name':'John'}],
 {2:[{'dept':2,'age':20, 'name':'Mary'},
    {'dept':2,'age':11, 'name':'Mark'},
    {'dept':2,'age':11, 'name':'Tom'}]
...
]
</code></pre>

<p>Now if I want to group using multiple keys say 'dept' and 'age', the above mentioned method returns</p>

<pre><code>[{(2, 20): [{'age': 20, 'dept': 2, 'name': 'Mary'}]},
 {(2, 11): [{'age': 11, 'dept': 2, 'name': 'Mark'},
            {'age': 11, 'dept': 2, 'name': 'Tom'}]},
 {(1, 10): [{'age': 10, 'dept': 1, 'name': 'Sam'}]},
 {(1, 12): [{'age': 12, 'dept': 1, 'name': 'John'}]}]
</code></pre>

<p>The desired output would be:</p>

<pre><code>[
    {
        2: {
            20: [
                {
                    'age': 20,
                    'dept': 2,
                    'name': 'Mary'
                }
            ]
        },
        {
            11: [
                {
                    'age': 11,
                    'dept': 2,
                    'name': 'Mark'
                },
                {
                    'age': 11,
                    'dept': 2,
                    'name': 'Tom'
                }
            ]
        }
    },
    {
        1: {
            10: [
                {
                    'age': 10,
                    'dept': 1,
                    'name': 'Sam'
                }
            ]
        },
        {
            12: [
                {
                    'age': 12,
                    'dept': 1,
                    'name': 'John'
                }
            ]
        }
    }
]
</code></pre>

<p>Can it be done with itertools? Or do I need to write that code myself?
Thanks.</p>
