Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting alphanumerical dictionary keys in python [duplicate]

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 ... ?

like image 240
Johanna Larsson Avatar asked Dec 28 '22 04:12

Johanna Larsson


2 Answers

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

like image 125
kennytm Avatar answered Dec 30 '22 17:12

kennytm


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')]*
like image 35
ceth Avatar answered Dec 30 '22 17:12

ceth