Building a list of dictionary values, sorted by key

Question:

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!

Asked By: rigidfence

||

Answers:

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)]
Answered By: kindall

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']]
Answered By: lc123
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.