Python sorters list, some shortcuts may be missing

How to sort a list of dictionaries where some labels for which I want to sort may be missing?

In particular, this list is from MPD and looks something like this:

[{'title':'Bad','album': 'XSCAPE','genre':'Pop'}, {'title': 'Down to', 'album': 'Money'}]

I would like to sort by genre, but note that the dictionary in the second element does not have a key for this.

Is there a built-in “Pythonic” method for this, or will I need to build my own sorting algorithm?

+4
source share
2 answers

Use the function sortedand .get:

l = [{'title':'Bad','album': 'XSCAPE','genre':'Pop'}, {'title': 'Down to', 'album': 'Money'}]
sorted_l = sorted(l, key=lambda x: x.get("genre", ""))
+9
source

You can use sortedand specify a key function:

output = sorted(input, key=lambda album: album['genre'] if 'genre' in album else '')

( '' ).

+2

Source: https://habr.com/ru/post/1663183/


All Articles