How do I sort a list of dictionaries where some labels for which I want to sort may be missing?
Specifically, this list is from MPD and looks something like the following...
[{'title':'Bad','album': 'XSCAPE','genre':'Pop'}, {'title': 'Down to', 'album': 'Money'}]
I would like to sort by genre, but note the dictionary in the second item has no key for that.
Is there a built in 'Pythonic' way to do this, or will I have to build my own sort algorithm?
Use sorted
function and .get
method:
l = [{'title':'Bad','album': 'XSCAPE','genre':'Pop'}, {'title': 'Down to', 'album': 'Money'}]
sorted_l = sorted(l, key=lambda x: x.get("genre", ""))
You can use sorted
, and specify a key function:
output = sorted(input, key=lambda album: album['genre'] if 'genre' in album else '')
This puts genre-less albums first in the list (because ''
is sorted before all other strings).
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