按自然顺序对字典键进行排序 [英] Sort Dictionary Keys in natural order

查看:89
本文介绍了按自然顺序对字典键进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按自然顺序"对字典键进行排序.如果我有一本带钥匙的字典

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"}

推荐答案

您可以将dict更改为

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')])

基本上,这里发生了什么,我将字符串分为字符串"部分和数字部分.数字部分更改为int,并且使用这两个值进行排序.

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.

这篇关于按自然顺序对字典键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆