Ticket #13828: 13828_dry_dictsort.diff

File 13828_dry_dictsort.diff, 1.4 KB (added by Satoru Logic, 14 years ago)
  • defaultfilters.py

     
    459459# LISTS           #
    460460###################
    461461
     462def _dictsort(value, arg, reverse=False):
     463    """
     464    Takes a list of dicts, returns that list sorted by the property given in
     465    the argument.
     466    The returned list will be in reverse order if `reverse` is `True`.
     467    """
     468    var_resolve = Variable(arg).resolve
     469    value.sort(key=lambda item: var_resolve(item), reverse=reverse)
     470    return value
     471
    462472def dictsort(value, arg):
    463473    """
    464474    Takes a list of dicts, returns that list sorted by the property given in
    465475    the argument.
    466476    """
    467     var_resolve = Variable(arg).resolve
    468     decorated = [(var_resolve(item), item) for item in value]
    469     decorated.sort()
    470     return [item[1] for item in decorated]
     477    return _dictsort(value, arg, reverse=False)
    471478dictsort.is_safe = False
    472479
    473480def dictsortreversed(value, arg):
     
    475482    Takes a list of dicts, returns that list sorted in reverse order by the
    476483    property given in the argument.
    477484    """
    478     var_resolve = Variable(arg).resolve
    479     decorated = [(var_resolve(item), item) for item in value]
    480     decorated.sort()
    481     decorated.reverse()
    482     return [item[1] for item in decorated]
     485    return _dictsort(value, arg, reverse=True)
    483486dictsortreversed.is_safe = False
    484487
    485488def first(value):
Back to Top