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.
We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.
Use a lambda function as key function to sort the list of dictionaries. Use the itemgetter function as key function to sort the list of dictionaries.
Sorting a dict by value descending using list comprehension. The quickest way is to iterate over the key-value pairs of your current dict and call sorted passing the dictionary values and setting reversed=True . If you are using Python 3.7, regular dict s are ordered by default.
>>> sorted(a, key=lambda i: i.values()[0], reverse=True)
[{43: 123}, {3: 103}, {36: 103}, {2: 102}, {23: 100}]
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.
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