Home > OS >  How to get unique values from a list of dictionaries?
How to get unique values from a list of dictionaries?

Time:03-29

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().

CodePudding user response:

Like this:

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

CodePudding user response:

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}

I also noticed that 'year' wasn't the only key containing the year data.

  • Related