Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of dicts by dict values

I have a list of dictionaries:

[{'title':'New York Times', 'title_url':'New_York_Times','id':4},
 {'title':'USA Today','title_url':'USA_Today','id':6},
 {'title':'Apple News','title_url':'Apple_News','id':2}]

I'd like to sort it by the title, so elements with A go before Z:

[{'title':'Apple News','title_url':'Apple_News','id':2},
 {'title':'New York Times', 'title_url':'New_York_Times','id':4},
 {'title':'USA Today','title_url':'USA_Today','id':6}]

What's the best way to do this? Also, is there a way to ensure the order of each dictionary key stays constant, e.g., always title, title_url, then id?

like image 930
ensnare Avatar asked May 20 '10 21:05

ensnare


People also ask

How do I sort a list of dictionaries by a value of the dictionary?

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.

How do you sort an array in a dictionary Python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.


1 Answers

l.sort(key=lambda x:x['title'])

To sort with multiple keys, assuming all in ascending order:

l.sort(key=lambda x:(x['title'], x['title_url'], x['id']))
like image 102
kennytm Avatar answered Oct 21 '22 15:10

kennytm