我有一个包含字典的列表,其中包含具有不同值的相同键。有没有一种方法可以跨不同的字典比较列表中的键?
例如;我有
title_must_include = ['some', 'title']
my_list = [{'title':'some title', 'year':2021},{'title':'another title', 'year':2018}]
现在我想遍历列表,看看哪些字典包含title_must_include
变量中包含的所有作品,然后比较年份,看看哪个是最近的,并返回符合该条件的字典。
谢谢
您可以使用列表推导,all
方法和max
来获得最近的年份
title_must_include = ['some', 'title']
my_list = [{'title': 'some title', 'year': 2021},
{'title': 'another title', 'year': 2018},
{'title': 'some other title', 'year': 2020}]
filtered_by_title = [i for i in my_list if all(w in i['title'] for w in title_must_include)]
item = max(filtered_by_title, key=lambda i: i['year'])
print(item) # {'title': 'some title', 'year': 2021}