Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do case insensitive sort of a dictionary and store them in OrderedDict

Tags:

python

sorting

I have the following dictionary of set:

named_sets  = {'DMXAA':set(['1441326_at', '1460062_at']), 'cdiGMP':set(['1441326_at', '1460062_at']),'cGAMP': set(['1441326_at', '1460062_at'])  }

What I want to do is to perform key sorting using case insensitive and stored them in OrderedDict yielding:

OrderedDict([ 
               ('cdiGMP', set(['1441326_at', '1460062_at'])),
               ('cGAMP', set(['1441326_at', '1460062_at'])),
               ('DMXAA', set(['1441326_at', '1460062_at'])),        
            ])

I tried this but failed:

from collections import OrderedDict
named_sets  = {'DMXAA':set(['1441326_at', '1460062_at']), 'cdiGMP':set(['1441326_at', '1460062_at']),'cGAMP': set(['1441326_at', '1460062_at'])  }
OrderedDict(sorted(named_sets.items()))

that gives:

OrderedDict([('DMXAA', set(['1441326_at', '1460062_at'])), ('cGAMP', set(['1441326_at', '1460062_at'])), ('cdiGMP', set(['1441326_at', '1460062_at']))])
like image 774
neversaint Avatar asked Jun 06 '15 08:06

neversaint


1 Answers

You'll need to provide a key function to sort case insensitively.

On Python 3 you'd use the str.casefold() function, on Python 2 sticking to str.lower() is fine:

OrderedDict(sorted(named_sets.items(), key=lambda i: i[0].lower()))

Note the lambda; you are sorting key-value pairs, but set objects are not orderable so you want to return just the key, folded to compare without case.

Demo:

>>> from collections import OrderedDict
>>> named_sets  = {'DMXAA':set(['1441326_at', '1460062_at']), 'cdiGMP':set(['1441326_at', '1460062_at']),'cGAMP': set(['1441326_at', '1460062_at'])  }
>>> OrderedDict(sorted(named_sets.items(), key=lambda i: i[0].lower()))
OrderedDict([('cdiGMP', set(['1441326_at', '1460062_at'])), ('cGAMP', set(['1441326_at', '1460062_at'])), ('DMXAA', set(['1441326_at', '1460062_at']))])
>>> _.keys()
['cdiGMP', 'cGAMP', 'DMXAA']
like image 88
Martijn Pieters Avatar answered Oct 03 '22 00:10

Martijn Pieters