Guest User

Douglas Soares de Andrad

a guest
Oct 16th, 2009
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. # coding: utf-8
  2.  
  3. import locale
  4.  
  5. def isorted(items, key):
  6.     """
  7.    Improved sorted (Locale aware sorted)
  8.    
  9.    Sorts a list of dictionaries/objects by key/attribute taking locales in
  10.    consideration.
  11.  
  12.    Example of use:
  13.    >>> data = [{'name': u'John Doe', 'age': 20},
  14.    ...         {'name': u'Jos� da Silva', 'age': 25},
  15.    ...         {'name': u'Almir Sarter', 'age': 35},
  16.    ...         {'name': u'Solim�es', 'age': 40},
  17.    ...         {'name': u'Al�rio', 'age': 10}]
  18.    
  19.    >>> names = isorted(data, 'name')
  20.    >>> for item in names:
  21.    ...     print repr(item['name'])
  22.    u'Al\\xc3\\xadrio'
  23.    u'Almir Sarter'
  24.    u'John Doe'
  25.    u'Jos\\xc3\\xa9 da Silva'
  26.    u'Solim\\xc3\\xb5es'
  27.    """
  28.    
  29.     # set the locale to be used if we have a locale set in the computer
  30.     default_locale = locale.getdefaultlocale()
  31.    
  32.     if None not in default_locale:
  33.         locale.setlocale(locale.LC_ALL, ".".join(default_locale))
  34.    
  35.     # Next, we sort the dictionary list, using locale-aware comparation and
  36.     # using a lambda expression to get unicode values with a trick:
  37.     # If the element is a dictionary it will use the dictionary get method,
  38.     # if it is a dictionary like object (django querysets) it will use the
  39.     # getattr builtin method to get the attribute (object.attribute).
  40.     # IMPORTANT: It will rise an exception if the key does not exists.
  41.     return sorted(items,
  42.                   cmp=locale.strcoll,
  43.                   key=lambda x: unicode(x.get(key) if isinstance(x,dict) \
  44.                                                    else getattr(x,key)))
  45.  
  46. if __name__ == "__main__":
  47.     import doctest, sys
  48.     doctest.testmod(sys.modules[__name__])
  49.  
  50.  
Advertisement
Add Comment
Please, Sign In to add comment