简体   繁体   English

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

[英]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().在我的问题中,我想看看缺少了哪些年份,所以我想我可以将它们列为一个 set()。

Like this:像这样:

unique_years = set([x['year'] for x in dicts])
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.我还注意到“年份”并不是包含年份数据的唯一键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM