I have the following list of dictionaries
a = [{23:100}, {3:103}, {2:102}, {36:103}, {43:123}]
How can I sort it:
a = [{43:123}, {3:103}, {36:103}, {2:102}, {23:100}]
I mean, sort the list by its dicts values, in descending order.
In addition to answering brandies, you can go with:
sorted(a, key=dict.values, reverse=True)
Pretty much the same, but perhaps more idiomatic.
>>> sorted(a, key=lambda i: i.values()[0], reverse=True) [{43: 123}, {3: 103}, {36: 103}, {2: 102}, {23: 100}]
key list.sort(), key:
key
list.sort()
>>> 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}]
- , d .values(). , . list.sort() , , .
d
.values()
I would prefer to use (or at least remember) .itervalues()
.itervalues()
In [25]: sorted(a, key=lambda x: x.itervalues().next, reverse=True) Out[25]: [{43: 123}, {36: 103}, {2: 102}, {23: 100}, {3: 103}]