Python按字母和数字排序字典键

时间:2014-06-10 03:52:06

标签: python sorting dictionary numerical

说我有这样的字典,

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

如果希望能够对此进行排序,那么

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

有没有一种方法可以按字母顺序对字典中的键进行排序,然后按数字排序?

1 个答案:

答案 0 :(得分:1)

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

sorted(d.keys())

您可以为sorted提供各种良好的排序功能,以满足您的渴望。 :)

鉴于如何命名键,排序函数可能看起来像......

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)

然后:

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