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?
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.
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.
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']))
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