Python排序列表,一些标签可能会丢失

Coo*_*lin 3 python sorting dictionary list

如何对可能缺少某些我想要排序的标签的词典列表进行排序?

具体来说,这个列表来自MPD,看起来如下......

[{'title':'Bad','album': 'XSCAPE','genre':'Pop'}, {'title': 'Down to', 'album': 'Money'}]
Run Code Online (Sandbox Code Playgroud)

我想按类型排序,但请注意第二项中的字典没有关键字.

有没有内置的'Pythonic'方法来做到这一点,还是我必须建立自己的排序算法?

Thy*_*st' 10

使用sorted功能和.get方法:

l = [{'title':'Bad','album': 'XSCAPE','genre':'Pop'}, {'title': 'Down to', 'album': 'Money'}]
sorted_l = sorted(l, key=lambda x: x.get("genre", ""))
Run Code Online (Sandbox Code Playgroud)


Blo*_*ard 3

您可以使用sorted, 并指定一个关键函数:

output = sorted(input, key=lambda album: album['genre'] if 'genre' in album else '')
Run Code Online (Sandbox Code Playgroud)

这会将无流派的专辑放在列表中的第一位(因为''在所有其他字符串之前排序)。