How to make case insensitive and store them in OrderedDict

I have the following set dictionary:

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 sort the keys using case insensitive and store them in an 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 couldn't:

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()))

      

which gives:

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

      

+3


source to share


1 answer


You will need to provide a function key

to subtly sort the case.

In Python 3, you should use a function str.casefold()

, in Python 2, sticking to str.lower()

, well:

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

      



Pay attention to lambda

; you are sorting key-value pairs, but the set

objects are not ordered, so you only want to return the key collapsed for comparison with no 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']

      

+2


source







All Articles