Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: utf-8
- import locale
- def isorted(items, key):
- """
- Improved sorted (Locale aware sorted)
- Sorts a list of dictionaries/objects by key/attribute taking locales in
- consideration.
- Example of use:
- >>> data = [{'name': u'John Doe', 'age': 20},
- ... {'name': u'Jos� da Silva', 'age': 25},
- ... {'name': u'Almir Sarter', 'age': 35},
- ... {'name': u'Solim�es', 'age': 40},
- ... {'name': u'Al�rio', 'age': 10}]
- >>> names = isorted(data, 'name')
- >>> for item in names:
- ... print repr(item['name'])
- u'Al\\xc3\\xadrio'
- u'Almir Sarter'
- u'John Doe'
- u'Jos\\xc3\\xa9 da Silva'
- u'Solim\\xc3\\xb5es'
- """
- # set the locale to be used if we have a locale set in the computer
- default_locale = locale.getdefaultlocale()
- if None not in default_locale:
- locale.setlocale(locale.LC_ALL, ".".join(default_locale))
- # Next, we sort the dictionary list, using locale-aware comparation and
- # using a lambda expression to get unicode values with a trick:
- # If the element is a dictionary it will use the dictionary get method,
- # if it is a dictionary like object (django querysets) it will use the
- # getattr builtin method to get the attribute (object.attribute).
- # IMPORTANT: It will rise an exception if the key does not exists.
- return sorted(items,
- cmp=locale.strcoll,
- key=lambda x: unicode(x.get(key) if isinstance(x,dict) \
- else getattr(x,key)))
- if __name__ == "__main__":
- import doctest, sys
- doctest.testmod(sys.modules[__name__])
Advertisement
Add Comment
Please, Sign In to add comment