Last Updated: February 25, 2016
·
463
· jmg

Slice objects in sublists sharing a common propery

Some times you want to slice a list of objects (or dictionaries) in sub-lists of objects that share a common property. In those cases you can use this simple snipet:

def slice(objects, prop):
    """
        slice objects in sub-lists sharing a common property
    """
    if not objects:
        return []

    def get_prop(obj, prop):
        if not isinstance(objects[0], dict):
            return obj.__dict__[prop]
        return obj[prop]

    objects_set = set([get_prop(o, prop) for o in objects])
    return [[o for o in objects if get_prop(o, prop) == obj] for obj in objects_set]