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!
To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
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)]
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With