Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Dictionary Keys in natural order [duplicate]

I want to sort dictionary keys in a "natural order". If I have a dictionary with the keys

    d = {"key1" : object, "key11" : object, "key2" : object, "key22" : object", "jay1" : object, "jay2" : object}

I want to sort this dictionary so the result is:

    d = { "jay1" : object, "jay2" : object, "key_1" : object, "key_2" : object, "key_11" : object, "key_22" : object"}
like image 529
user2909250 Avatar asked Jun 12 '14 03:06

user2909250


2 Answers

You can change your dict into OrderedDict:

import collections, re

d = {"key1" : 'object', "key11" : 'object', "key2" : 'object', "key22" : 'object', "jay1" : 'object', "jay2" : 'object'}


my_fun = lambda k,v: [k, int(v)]

d2 = collections.OrderedDict(sorted(d.items(), key=lambda t: my_fun(*re.match(r'([a-zA-Z]+)(\d+)',t[0]).groups())))

print(d2)
#reslt: OrderedDict([('jay1', 'object'), ('jay2', 'object'), ('key1', 'object'), ('key11', 'object'), ('key2', 'object'), ('key22', 'object')])

Basically, what is happening here, that I split the strings into 'string' part and number part. Number part is changed to int, and the sorting happens using these two values.

like image 95
Marcin Avatar answered Oct 25 '22 03:10

Marcin


As others have said, dictionaries are not ordered. However, if you want to iterate through these keys in a natural order, you could do something like the following:

d = {"key1" : object, "key11" : object, "key2" : object, "key22" : object, "jay1" : object, "jay2" : object}
sortedKeys = sorted(d.keys())
print sortedKeys
for key in sortedKeys:
    print d[key]
like image 31
Bryan Avatar answered Oct 25 '22 01:10

Bryan