Skip to content Skip to sidebar Skip to footer

Grouping Python Dictionaries In Hierarchical Form

I have a list of dictionaries and I wanted to group the data. I used the following: group_list = [] for key, items in itertools.groupby(res, operator.itemgetter('dept')): group

Solution 1:

Absolutely. You just need to apply itertools.groupby() for the second criterion first, then the other.


Solution 2:

You would need to write a (probably recursive) bit of code to do this yourself - itertools doesn't have a tree-builder in it.


Solution 3:

Thanks everyone for your help. Here is how I did it:

import itertools, operator

l = [{'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'}]

groups = ['dept', 'age', 'name'] 

groups.reverse()
def hierachical_data(data, groups):
    g = groups[-1]
    g_list = []
    for key, items in itertools.groupby(data, operator.itemgetter(g)):
        g_list.append({key:list(items)})
    groups = groups[0:-1]
    if(len(groups) != 0):
        for e in g_list:
            for k,v in e.items():
                e[k] = hierachical_data(v, groups)

    return g_list

print hierachical_data(l, groups)

Post a Comment for "Grouping Python Dictionaries In Hierarchical Form"