【问题标题】:Sorting dictionary with alphanumeric keys in natural order [duplicate]使用自然顺序的字母数字键对字典进行排序[重复]
【发布时间】:2018-02-19 10:13:01
【问题描述】:

我有一本 python 字典:

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

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

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

有没有办法按自然顺序获取:

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

谢谢。

【问题讨论】:

    标签: python sorting dictionary


    【解决方案1】:

    你很幸运:natsort 模块可以提供帮助。首先,使用以下方式安装它:

    pip install natsort
    

    现在,您可以将d.keys() 传递给natsort.natsorted,并构建一个新的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's answer得到这个想法):

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

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

    【讨论】:

      【解决方案2】:

      在字符代码上使用chr() 函数的短“技巧”(无外部包):

      import collections
      
      d = {'a1': 123, 'a2': 2, 'a10': 333, 'a11': 4456}
      result = collections.OrderedDict(sorted(d.items(), key=lambda x: chr(int(x[0][1:]))))
      print(result)
      

      输出:

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

      【讨论】:

      • 但是当key为'aa11'时会报错
      • @Jeril,您没有提到输入可能是任意的。这适用于您当前的输入格式
      猜你喜欢
      • 2014-08-02
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 2015-04-06
      相关资源
      最近更新 更多