我需要根据键对字典进行排序,然后返回与这些键关联的值。
ages = {40 : 'mother', 38 : 'father', 17 : 'me'}
['me', 'father', 'mother'] # Should return this
最快的方法是什么(性能对我来说确实是一个问题,因为排序在我的代码中被调用了数千次)。
非常感谢!
我需要根据键对字典进行排序,然后返回与这些键关联的值。
ages = {40 : 'mother', 38 : 'father', 17 : 'me'}
['me', 'father', 'mother'] # Should return this
最快的方法是什么(性能对我来说确实是一个问题,因为排序在我的代码中被调用了数千次)。
非常感谢!
由于您的键是数字的,并且默认情况下字典上的迭代器返回键 - 您可以直接对键进行排序:
>>> ages = {40:'mother', 38:'father', 17:'me'}
>>> [ages[k] for k in sorted(ages)]
['me', 'father', 'mother']
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')
PS 如果字典非常大,您可能需要考虑dict.iteritems()
在 Python 2 上使用 which 返回迭代器。在 Python 3 上,这是默认行为,它由dict.items()
.
替代解决方案 - 使用operator.itemgetter()
:
>>> import operator
>>> operator.itemgetter(*sorted(ages))(ages)
('me', 'father', 'mother')
由于此类集合的性质,您无法对字典进行排序。尽管 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.