Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get keys/values from sorted OrderedDict.
from collections import OrderedDict
d = {'A': 3,
'B': 2,
'C': 1}
OrderedDict(sorted(d.items(), key=lambda x: x[0])).values()
# Out[1]: odict_values([3, 2, 1])
OrderedDict(sorted(d.items(), key=lambda x: x[1])).values()
# Out[2]: odict_values([1, 2, 3])
OrderedDict(sorted(d.items(), key=lambda x: x[0])).keys()
# Out[3]: odict_keys(['A', 'B', 'C'])
OrderedDict(sorted(d.items(), key=lambda x: x[1])).keys()
# Out[4]: odict_keys(['C', 'B', 'A'])
# reverse
OrderedDict(sorted(d.items(), key=lambda x: x[0], reverse=True)).values()
# Out[5]: odict_values([1, 2, 3])
# get list
list(OrderedDict(sorted(d.items(), key=lambda x: x[0])).values())
# Out[6]: [3, 2, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.