user1403568
user1403568

Reputation: 493

Sorting a list of dicts by dict values

I have the following list of dictionaries

a = [{23:100}, {3:103}, {2:102}, {36:103}, {43:123}]

How can I sort it to get:

a = [{43:123}, {3:103}, {36:103}, {2:102}, {23:100}]

I mean, to sort the list by its dicts' values, in descending order.

Upvotes: 6

Views: 2086

Answers (5)

Aran-Fey
Aran-Fey

Reputation: 43316

In python 3, the other answers no longer work because dict.values() now returns a dict view object rather than a list. To extract the value from the view object, we can use a combination of iter and next:

a.sort(key=lambda dic: next(iter(dic.values())), reverse=True)

Upvotes: 1

KurzedMetal
KurzedMetal

Reputation: 12946

I'd rather use (or at least keep in mind) .itervalues()

In [25]: sorted(a, key=lambda x: next(x.itervalues()), reverse=True)
Out[25]: [{43: 123}, {36: 103}, {2: 102}, {23: 100}, {3: 103}]

Upvotes: 0

brandizzi
brandizzi

Reputation: 27090

You can pass a key parameter to the list.sort() method, so the comparison will be made in function of the returning value of key:

>>> a = [{23:100}, {3:103}, {2:102}, {36:103}, {43:123}]
>>> a.sort(key=lambda d: d.values()[0], reversed=True)
>>> a
[{23: 100}, {2: 102}, {3: 103}, {36: 103}, {43: 123}]

In this case, the key is a function which receives a dictionary d and gets a list of its value with .values(). Since there is just one value, we get this only value from the returned list. Then, the list.sort() method will compare those returned values, instead of the dictionaries themselves, when sorting.

Upvotes: 1

In addition to brandizzi's answer, you could go with:

sorted(a, key=dict.values, reverse=True)

Pretty much the same thing, but possibly more idiomatic.

Upvotes: 6

fraxel
fraxel

Reputation: 35319

>>> sorted(a, key=lambda i: i.values()[0], reverse=True)
[{43: 123}, {3: 103}, {36: 103}, {2: 102}, {23: 100}]

Upvotes: 3

Related Questions