我只是想计算python列表中字典列表的出现次数。我想附加
count
基于某种过滤的出现。我看到了一个在django模型中实现这一点的示例。我只是不知道如何以纯粹的Python方式实现这种方法。
类似的方法,但有和,我只需要计数,
Count the values in list of dictionaries python
dataset =[
{
'Country': 'GB',
'Pollutant': 'SO2',
'Pollution': 10,
'Year': 2016
},
{
'Country': 'AL',
'Pollutant': 'O3',
'Pollution': 10,
'Year': 2015
},
{
'Country': 'BE',
'Pollutant': 'SO2',
'Pollution': 5,
'Year': 2016
},
{
'Country': 'GB',
'Pollutant': 'SO2',
'Pollution': 10,
'Year': 2016
},
{
'Country': 'BE',
'Pollutant': 'SO2',
'Pollution': 10,
'Year': 2016
},
]
all_Years = sorted(set([v['Year'] for v in dataset]))
all_countries = sorted(set([v['Country'] for v in dataset]))
print(all_Years)
print(all_countries)
for country in all_countries:
new_data = {
'years': all_Years,
'country': country,
'data' : []
}
for year in all_Years:
#some sort of filter function to apply like in django models
f = Q(year = year, country=country)
#apply that filltering
country_count = dataset.filter(f).count()
new_data['data'].append(country_count if country_count else 0)
#expected output
#new_data =
[{'years': [2015,2016], 'country': 'AL', 'data': [1, 0]},
{'years': [2015,2016], 'country': 'BE', 'data': [1, 2]},
{'years': [2015,2016], 'country': 'GB', 'data': [0, 2]}]