4

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

Johanna Larsson
  • 10,531
  • 6
  • 39
  • 50
  • These answers are outdated. A simpler solution using `natsort` may be found [here](https://stackoverflow.com/questions/46151132/sorting-dictionary-with-alphanumeric-keys-in-natural-order/46151175#46151175). – cs95 Sep 11 '17 at 08:37

3 Answers3

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

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • That's fine, the keys will always be the same. This is very readable and the kind of thing I was looking for. – Johanna Larsson Nov 23 '10 at 08:25
  • Or, (a slight varient): `keys.sort(key=lambda x:x[0]+x[1:].zfill(5))` (moved from an answer on a suggestion by @AalokParikh) – JesseW Aug 19 '12 at 23:55
1

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')]*
ceth
  • 44,198
  • 62
  • 180
  • 289
0

You need OrderedDict from collections in 2.7 +

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91