Skip to content

Instantly share code, notes, and snippets.

@filipeximenes
Last active March 22, 2016 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filipeximenes/72acd46aec6548eac1da to your computer and use it in GitHub Desktop.
Save filipeximenes/72acd46aec6548eac1da to your computer and use it in GitHub Desktop.
Categorize
def categorize(lst, attrs):
"""
Generate a dictionary of lists where the keys are generated from
some specified attribute of the items in the list
"""
def dive_in(obj, attrs, index=0):
if not obj or index >= len(attrs):
return obj
new_obj = getattr(obj, attrs[index])
if len(attrs) > 0:
return dive_in(new_obj, attrs, index+1)
return new_obj
categories = {}
for item in lst:
value = dive_in(item, attrs)
if value not in categories:
categories[value] = []
categories[value].append(item)
return categories
categorize(SomeModel.objects.all(), ['related_obj', 'related_obj_attr'])
# Result
{
"value": [
obj1,
obj2
],
"other_value": [
obj3
],
}
# OR
categories = groupby(affiliates, lambda x: x.category.slug if x.category else None)
categories = {a:list(b) for a, b in categories}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment