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]
Written by Juan Manuel García
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#