Sort dictionary by key using locale/collation

后端 未结 2 581
梦如初夏
梦如初夏 2021-02-13 19:28

The following code is ignoring the locale and Égypt goes at the end, what\'s wrong?

dict = {\"United States\": \"United States\", \"Spain\" : \"Spain\", \"Englan         


        
2条回答
  •  梦谈多话
    2021-02-13 19:44

    Consider the following...

    import unicodedata
    from collections import OrderedDict
    dict = {"United States": "United States", "Spain" : "Spain", "England": "England", "Égypt": "Égypt"}
    
    import locale
    
    # using your default locale (user settings)
    locale.setlocale(locale.LC_ALL,"fr_FR")
    
    print OrderedDict(sorted(dict.items(),cmp= lambda a,b: locale.strcoll(unicodedata.normalize('NFD', unicode(a)[0]).encode('ASCII', 'ignore'),
                                                                           unicodedata.normalize('NFD', unicode(b)[0]).encode('ASCII', 'ignore'))))
    

提交回复
热议问题