关于排序:python按字母和数字对字典键进行排序

Python sort dictionary keys by letters and then numbers

本问题已经有最佳答案,请猛点这里访问。

比如说我有一本这样的字典,

1
d = {"John1" :"blah blah","John2" :"blah blah","John11" :"blah blah","Dave1" :"blah blah","Dave2" :"blah blah","Dave13" :"blah blah","Dave23" :"blah blah"}

如果想把这个分类,就这样吧

1
d = {"Dave1" :"blah blah","Dave2" :"blah blah","Dave13" :"blah blah","Dave23" :"blah blah","John1" :"blah blah","John2" :"blah blah","John11" :"blah blah", }

有没有一种方法可以把这本字典的键按字母顺序排序,然后按数字排序?


请记住,对字典本身进行排序实际上不是数据结构的预期用途,但是如果您只是在查找字典键的已排序列表:

1
sorted(d.keys())

在这里,您可以提供各种良好的排序功能,以满足您不断燃烧的愿望。:)

考虑到键的命名方式,排序函数可能看起来像…

1
2
3
4
5
6
def my_key(item):
    alpha = ''.join(i for i in item if i.isalpha())
    num = ''.join(i for i in item if i.isdigit())
    if num:
        return (alpha, int(num))
    return (alpha, 0)

然后:

1
sorted(d.keys(), key=my_key)