使用字母数字键以自然顺序对字典进行排序 [英] Sorting dictionary with alphanumeric keys in natural order

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

问题描述

我有一个python字典:

I have a python dictionary:

d = {'a1': 123, 'a2': 2, 'a10': 333, 'a11': 4456}

当我使用OrderedDict对字典进行排序时,得到以下输出:

When I sort the dictionary using OrderedDict I get the following output:

from collections import OrderedDict
OrderedDict(sorted(d.items()))
# Output
# OrderedDict([('a1', 123), ('a10', 333), ('a11', 4456), ('a2', 2)])

有没有一种以自然顺序获取它的方法:

Is there a way to get it in the natural order:

OrderedDict([('a1', 123), ('a2', 2), ('a10', 333), ('a11', 4456)])
or 
{'a1': 123, 'a2': 2, 'a10': 333, 'a11': 4456}

谢谢.

推荐答案

您很幸运: natsort 模块可以提供帮助.首先,使用以下命令进行安装:

You're in luck: The natsort module can help. First, install it using:

pip install natsort

现在,您可以将d.keys()传递给natsort.natsorted,并构建一个新的OrderedDict.

Now, you can pass d.keys() to natsort.natsorted, and build a new OrderedDict.

import natsort
from collections import OrderedDict

d = {'a1' : 123, 
     'a2' : 2, 
     'a10': 333, 
     'a11': 4456}
keys = natsort.natsorted(d.keys())    
d_new = OrderedDict((k, d[k]) for k in keys)

一个简短的版本涉及对d.items()进行排序( RomanPerekhrest的答案 中得到了这个想法) :

A shorter version involves sorting d.items() (got this idea from RomanPerekhrest's answer):

d_new = OrderedDict(natsort.natsorted(d.items()))


d_new
OrderedDict([('a1', 123), ('a2', 2), ('a10', 333), ('a11', 4456)])

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

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