Reputation: 335
I have a python dictionary that looks something like this:
attributes = {
'size': ['s','m','l'],
'color': ['black', 'orange'],
}
I want to get a list of values. If I use values()
, I get this:
>>> attributes.values()
[['black', 'orange'], ['s', 'm', 'l']]
However, I want the resulting list of lists to be sorted by the dictionary key in reverse order -- ie, size and then color, not color and then size. I want this:
[['s', 'm', 'l'], ['black', 'orange']]
I do not necesarilly know what the dictionary keys will be beforehand, but I do always know if I want them in alphabetical or reverse alphabetical order.
Is there some pythonic way to do this?
The only thing I can think of seems... not very python-like:
keys = sorted(attributes.keys(), reverse=True)
result = []
for key in keys:
result.append(attributes[key])
It's hard to go from attributes.values()
to all of that just to sort the list!
Upvotes: 32
Views: 26601
Reputation: 158
The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:
import collections
result = collections.OrderedDict(sorted(attributes.items(), reverse=True))
>>> result.values()
[['s', 'm', 'l'], ['black', 'orange']]
Upvotes: 3
Reputation: 184161
This code:
keys = sorted(attributes.keys(), reverse=True)
result = []
for key in keys:
result.append(attributes[key])
Is basically the use case for which list comprehensions were invented:
result = [attributes[key] for key in sorted(attributes.keys(), reverse=True)]
Upvotes: 49