Reputation: 14845
I need to sort a dictionary based on the keys, and then return the values associated with those keys.
ages = {40 : 'mother', 38 : 'father', 17 : 'me'}
['me', 'father', 'mother'] # Should return this
What is the fastest possible way of doing this (performance is really an issue for me, as the sorting gets called thousands of times throughout my code).
Thank you very much!
Upvotes: 0
Views: 169
Reputation: 9104
Making use of the sorted()
and zip()
functions:
zip(*sorted(ages.items(), key=lambda item: item[0]))[1]
First it sorts the dictionary creating a list of tuples (the items):
>>> sorted(ages.items())
[(17, 'me'), (38, 'father'), (40, 'mother')]
Then it takes only the values:
>>> zip(*sorted(ages.items())[1]
('me', 'father', 'mother')
P.S. If the dictionary is very big you may want to consider using dict.iteritems()
which on Python 2 returns an iterator. On Python 3 this is the default behaviour and it is provided by dict.items()
.
Alternative solution - using operator.itemgetter()
:
>>> import operator
>>> operator.itemgetter(*sorted(ages))(ages)
('me', 'father', 'mother')
Upvotes: 3
Reputation: 22659
You can't sort a dictionary due to the nature of this kind of collections. Although Python gives you several options: either use OrderedDict
(to keep the order of inserted key/value pairs), or just sort the keys, e.g.::
ages = {40 : 'mother', 38 : 'father', 17 : 'me'}
ages_sorted = sorted(ages)
# or ages.iterkeys() / .keys() (in Py3) which is a bit self-explanatory.
Upvotes: 2
Reputation: 174614
Since your keys are numeric and by default iterators over dictionaries return the keys - you can sort the keys directly:
>>> ages = {40:'mother', 38:'father', 17:'me'}
>>> [ages[k] for k in sorted(ages)]
['me', 'father', 'mother']
Upvotes: 4