python-3.xdictionarydictionary-comprehensionset-comprehension

How to get unique values from a list of dictionaries?


I have 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'}]

and I want to list the unique years only, how can I do that?

with this, I can get all values:

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

while this code lists everything unique:

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

in my problem, I want to see which years are missing, so I thought I could list them as a set().


Solution

  • Like this:

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