Sort Dictionary Keys in natural order
本问题已经有最佳答案,请猛点这里访问。
我想按"自然顺序"对字典键进行排序。如果我有带钥匙的字典
1 | d = {"key1" : object,"key11" : object,"key2" : object,"key22" : object","jay1" : object,"jay2" : object} |
我想对这本词典进行排序,结果是:
1 | d = {"jay1" : object,"jay2" : object,"key_1" : object,"key_2" : object,"key_11" : object,"key_22" : object"} |
您可以将听写改为顺序信息:
1 2 3 4 5 6 7 8 9 10 11 | 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')]) |
基本上,这里发生的是,我把字符串分成"字符串"部分和"数字"部分。数字部分更改为
正如其他人所说,字典是不需要订购的。但是,如果您希望按自然顺序迭代这些键,可以执行如下操作:
1 2 3 4 5 | 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] |
您不能订购
1 2 | d = {"key1" : object,"key11" : object,"key2" : object,"key22" : object,"jay1" : object,"jay2" : object} print natsort.natsorted(d.items()) #[('jay1', <type 'object'>), ('jay2', <type 'object'>), ('key1', <type 'object'>), ('key2', <type 'object'>), ('key11', <type 'object'>), ('key22', <type 'object'>)] |
在python中,