在python中排序字母数字字典键

时间:2010-11-23 07:43:17

标签: python sorting dictionary

我有一个字典,如A1-A15,B1-B15等。运行dictionary.keys()。sort()导致A1,A10,A11 ...

def sort_keys(dictionary):
    keys = dictionary.keys()
    keys.sort()
    return map(dictionary.get, keys)

如何对它进行排序,使它们按顺序排列,即A1,A2,A3 ......?

3 个答案:

答案 0 :(得分:9)

keys.sort(key=lambda k:(k[0], int(k[1:])) )

编辑:这将失败,因为密钥不像A23,例如AA12将停止该计划。在一般情况下,请参阅Python analog of natsort function (sort a list using a "natural order" algorithm)

答案 1 :(得分:1)

dictionary.keys()返回一个列表,您可以按自己的函数对列表进行排序:

>>> a = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]
>>> import operator
>>> a.sort(key = operator.itemgetter(1))
>>> a
[(u'.', '.'), (u'we', 'PRP'), (u'you', 'PRP'), (u'saw', 'VBD'), (u'bruh', 'VBP')]*

答案 2 :(得分:0)

您需要2.7 +

中的集合中的OrderedDict
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])