Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 436
user1403568 Avatar asked Jun 06 '12 13:06

user1403568


People also ask

Can you sort a list of dictionaries in Python?

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.

How do you sort two dictionaries in Python?

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.

How do you sort a dictionary by value in Python descending?

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.


2 Answers

>>> sorted(a, key=lambda i: i.values()[0], reverse=True)
[{43: 123}, {3: 103}, {36: 103}, {2: 102}, {23: 100}]
like image 40
fraxel Avatar answered Oct 05 '22 02:10

fraxel


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.

like image 177
Hod - Monica's Army Avatar answered Oct 05 '22 03:10

Hod - Monica's Army