Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a list of dictionary values, sorted by key

Tags:

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!

like image 809
rigidfence Avatar asked Apr 14 '16 22:04

rigidfence


People also ask

How do I sort a list of dictionaries by key?

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.

Can dictionary be sorted by keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

Can you sort values in a dictionary?

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.


2 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)] 
like image 76
kindall Avatar answered Nov 22 '22 02:11

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']] 
like image 42
lc123 Avatar answered Nov 22 '22 02:11

lc123