Last active
March 22, 2016 22:36
-
-
Save filipeximenes/72acd46aec6548eac1da to your computer and use it in GitHub Desktop.
Categorize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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