通过键对值在Python中对字典进行排序

时间:2012-10-14 11:26:22

标签: python

我需要根据键对字典进行排序,然后返回与这些键关联的值。

ages = {40 : 'mother', 38 : 'father', 17 : 'me'}
['me', 'father', 'mother']  # Should return this

执行此操作的最快方法是什么(性能对我来说确实是一个问题,因为在我的代码中,排序会被调用数千次。)

非常感谢!

3 个答案:

答案 0 :(得分:4)

由于您的键是数字的,默认情况下,字典上的迭代器会返回键 - 您可以直接对键进行排序:

>>> ages = {40:'mother', 38:'father', 17:'me'}
>>> [ages[k] for k in sorted(ages)]
['me', 'father', 'mother']

答案 1 :(得分:3)

使用sorted()zip()函数:

zip(*sorted(ages.items(), key=lambda item: item[0]))[1]

首先,它对字典进行排序,创建元组列表(项目):

>>> sorted(ages.items())
[(17, 'me'), (38, 'father'), (40, 'mother')]

然后只需要值:

>>> zip(*sorted(ages.items())[1]
('me', 'father', 'mother')

P.S。如果字典非常大,您可能需要考虑使用{2}在Python 2上返回迭代器。在Python 3上,这是默认行为,它由dict.iteritems()提供。


替代解决方案 - 使用dict.items()

>>> import operator
>>> operator.itemgetter(*sorted(ages))(ages)
('me', 'father', 'mother')

答案 2 :(得分:2)

由于此类集合的性质,您无法对字典进行排序。虽然Python为您提供了几个选项:使用OrderedDict(保持插入的键/值对的顺序),或者只是对键进行排序,例如::。

ages = {40 : 'mother', 38 : 'father', 17 : 'me'}
ages_sorted = sorted(ages) 
# or ages.iterkeys() / .keys() (in Py3) which is a bit self-explanatory.