如何根据ONE键类型的值对字典列表进行排序



我有以下字典列表:

[{'title': 'Shrek the Musical',   'year': 2013,   'genres': ['Comedy', 'Family', 'Fantasy'],   'duration': 130,   'directors': ['Michael John Warren'],   'actors': ["Brian d'Arcy James", 'Sutton Foster', 'Christopher Sieber'],   'rating': 7.0},
{'title': 'Shrek Retold',   'year': 2018,   'genres': ['Animation', 'Adventure', 'Comedy'],   'duration': 90,   'directors': ['Grant Duffrin'],   'actors': ['Harry Antonucci', 'Russell Bailey'],   'rating': 7.5},  
{'title': 'Shrek 2',   'year': 2004,   'genres': ['Animation', 'Adventure', 'Comedy'],   'duration': 93,   'directors': ['Andrew Adamson', 'Kelly Asbury'],   'actors': ['Mike Myers', 'Eddie Murphy'],   'rating': 7.2},  
{'title': 'Shrek the Third',   'year': 2007,   'genres': ['Animation', 'Adventure', 'Comedy'],   'duration': 93,   'directors': ['Chris Miller', 'Raman Hui'],   'actors': ['Mike Myers', 'Eddie Murphy', 'Cameron Diaz', 'Antonio Banderas'],   'rating': 6.1}, 
{'title': 'Shrek Forever After',   'year': 2010,   'genres': ['Animation', 'Adventure', 'Comedy'],   'duration': 93,   'directors': ['Mike Mitchell'],   'actors': ['Mike Myers', 'Eddie Murphy', 'Cameron Diaz', 'Antonio Banderas'],   'rating': 6.3}, 
{'title': 'Shrek',   'year': 2001,   'genres': ['Animation', 'Adventure', 'Comedy'],   'duration': 90,   'directors': ['Andrew Adamson', 'Vicky Jenson'],   'actors': ['Mike Myers', 'Eddie Murphy'],   'rating': 7.8}]

我想制作一份电影列表,按上映年份的升序排列。也就是说,排序应该只依赖于一个值,忽略所有其他键。

我尝试使用sorted函数,但我不知道如何指定字典应该基于单个值进行排序。

您可以将key参数传递给sorted(),告诉它在哪个键上排序:

result = sorted(data, key=lambda x: x['year'])
print(result)

该输出:

[{'title': 'Shrek', 'year': 2001, 'genres': ['Animation', 'Adventure', 'Comedy'], 'duration': 90, 'directors': ['Andrew Adamson', 'Vicky Jenson'], 'actors': ['Mike Myers', 'Eddie Murphy'], 'rating': 7.8},
{'title': 'Shrek 2', 'year': 2004, 'genres': ['Animation', 'Adventure', 'Comedy'], 'duration': 93, 'directors': ['Andrew Adamson', 'Kelly Asbury'], 'actors': ['Mike Myers', 'Eddie Murphy'], 'rating': 7.2},
{'title': 'Shrek the Third', 'year': 2007, 'genres': ['Animation', 'Adventure', 'Comedy'], 'duration': 93, 'directors': ['Chris Miller', 'Raman Hui'], 'actors': ['Mike Myers', 'Eddie Murphy', 'Cameron Diaz', 'Antonio Banderas'], 'rating': 6.1},
{'title': 'Shrek Forever After', 'year': 2010, 'genres': ['Animation', 'Adventure', 'Comedy'], 'duration': 93, 'directors': ['Mike Mitchell'], 'actors': ['Mike Myers', 'Eddie Murphy', 'Cameron Diaz', 'Antonio Banderas'], 'rating': 6.3},
{'title': 'Shrek the Musical', 'year': 2013, 'genres': ['Comedy', 'Family', 'Fantasy'], 'duration': 130, 'directors': ['Michael John Warren'], 'actors': ["Brian d'Arcy James", 'Sutton Foster', 'Christopher Sieber'], 'rating': 7.0},
{'title': 'Shrek Retold', 'year': 2018, 'genres': ['Animation', 'Adventure', 'Comedy'], 'duration': 90, 'directors': ['Grant Duffrin'], 'actors': ['Harry Antonucci', 'Russell Bailey'], 'rating': 7.5}]

最新更新