I have a dictionary of keys like A1-A15, B1-B15 etc. Running dictionary.keys().sort() results in A1, A10, A11 ...
def sort_keys(dictionary):
keys = dictionary.keys()
keys.sort()
return map(dictionary.get, keys)
How do I sort it so that they get in the right order, ie A1, A2, A3 ... ?
keys.sort(key=lambda k:(k[0], int(k[1:])) )
Edit: This will fail in the keys are not like A23, e.g. AA12 will stop the program. In the general case, see Python analog of natsort function (sort a list using a "natural order" algorithm).
dictionary.keys() return a list and you can sort list by your own function:
>>> a = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]
>>> import operator
>>> a.sort(key = operator.itemgetter(1))
>>> a
[(u'.', '.'), (u'we', 'PRP'), (u'you', 'PRP'), (u'saw', 'VBD'), (u'bruh', 'VBP')]*
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