Search code examples
pythondictionarypython-unicodeordereddictionary

In python, how to order a dict with unicode content?


I've the following dict:

<type 'dict'>
{u'010-010': u'010-010_comp_v000', u'012-010': u'012-010_comp_v002', u'007-010': u'007-010_comp_v000', u'006-010': u'006-010_comp_v009', u'005-010': u'005-010_comp_v002'}

I want to order it by keys. But using Collections and OrderedDict, I can't get it working.

OrderedDict([(u'010-010', u'010-010_comp_v000'), (u'012-010', u'012-010_comp_v002'), (u'007-010', u'007-010_comp_v000'), (u'006-010', u'006-010_comp_v009'), (u'005-010', u'005-010_comp_v002')])

I assume it is linked to unicode? Is there a solution to correct this without having to rewrite the dict? It's an output of another soft so I can't change the type easily.

The desired output is: '005-010'... '006-010'... '007-010'...


Solution

  • OrderDicts retain insertion order - they don't sort the items for you. You'll need to sort them yourself:

    d = {u'010-010': u'010-010_comp_v000', u'012-010': u'012-010_comp_v002', u'007-010': u'007-010_comp_v000', u'006-010': u'006-010_comp_v009', u'005-010': u'005-010_comp_v002'}
    o = OrderedDict((k, v) for k, v in sorted(d.items()))
    print(o)