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']))])
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With