如何从字典列表中获取唯一值?

How to get unique values from a list of dictionaries?

我有一个词典列表:

dicts = [{'year':2020, 'target':'usd'}, {'year':2019, 'target':'eur'}, {'year':2018, 'target':'eur'}, {'year':2018, 'target':'eur'}, {'year':2016, 'target':'eur'}]

我只想列出唯一的年份,我该怎么做?

有了这个,我可以获得所有值:

unique_years = [{value for (key,value) in dct.items() if key=='date'} for dct in dicts]
unique_years
Output:
[{2020}, {2019}, {2018}, {2018}, {2016}]

虽然这段代码列出了所有独特的东西:

list(set(val for dic in dicts for val in dic.values()))
Output:
[2016, 2018, 2019, 2020, 'usd', 'eur']

在我的问题中,我想看看缺少了哪些年份,所以我想我可以将它们列为一个 set()。

unique_years = set()
for a_dict in dicts:
    year = a_dict.get('year') or a_dict.get('date')
    unique_years.add(year)
print(unique_years) # {2016, 2018, 2019, 2020}

我还注意到 'year' 不是唯一包含年份数据的键。

像这样:

unique_years = set([x['year'] for x in dicts])