Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sort list of dictionaries, some labels may be missing

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?

like image 765
Cool Javelin Avatar asked Dec 10 '22 13:12

Cool Javelin


2 Answers

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", ""))
like image 99
Thyrst' Avatar answered Feb 23 '23 01:02

Thyrst'


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).

like image 32
Blorgbeard Avatar answered Feb 23 '23 02:02

Blorgbeard