-1

Say I have a dictionary like this,

d = {"John1" : "blah blah", "John2" : "blah blah", "John11" : "blah blah", "Dave1" : "blah blah", "Dave2" : "blah blah", "Dave13" : "blah blah", "Dave23" : "blah blah"}

If want to be able to sort this so it is

d = {"Dave1" : "blah blah", "Dave2" : "blah blah", "Dave13" : "blah blah", "Dave23" : "blah blah", "John1" : "blah blah", "John2" : "blah blah", "John11" : "blah blah", }

Is there a way I can sort the keys of this dictionary alphabetically, then numerically?

user2909250
  • 261
  • 5
  • 10
  • 6
    It is not possible to sort a dict, only to get a representation of a dict that is sorted. – Alok Jun 10 '14 at 03:54

1 Answers1

1

Keep in mind that sorting the dictionary itself is really not what the data structure is intended for, but if you are looking for just a sorted list of the dictionary keys:

sorted(d.keys())

Where you can provide sorted with all sorts of good sorting functions to satisfy what ever burning desire you have. :)

Given how the keys are named a sorting function might look like...

def my_key(item):
    alpha = ''.join(i for i in item if i.isalpha())
    num = ''.join(i for i in item if i.isdigit())
    if num:
        return (alpha, int(num))
    return (alpha, 0)

and then:

sorted(d.keys(), key=my_key)
MrAlias
  • 1,316
  • 15
  • 26