I have I have such a datastructure:
dataset = [{'country': 'Afghanistan',
'continent': 'Asia',
'1990': 500,
'1991': 500,
'1992': 500,
'1993': 1000},
{'country': 'Albania',
'continent': 'Europe',
'1990': 100,
'1991': 100,
'1992': 100,
'1993': 100}
{'country': 'Algeria',
'continent': 'Africa',
'1990': 500,
'1991': 500,
'1992': 1000,
'1993': 1000
}]
I need to find max value in year 1991 and create a dictionary with keys - country, where this maximum value was, the year we are looking for (1991) and the maximum value found.
I was thinking of making it that way, but it didn't work.
new_dict = {}
str_year = str(year)
for dict_ in dataset:
for key, values in dict_.items():
max_val = max(dict_, key=lambda x:x[str_year])
new_dict = {'country' : dict_['country'], 'year': year, 'cases': max_val}
return new_dict
How can I do this?
CodePudding user response:
You don't need to iterate through the list of dictionaries - max()
will give you the one you want to work with. Then you just need to extract the correct fields, like this:
max_val = max(dataset, key=lambda x:x[str_year])
new_dict = {'country' : max_val['country'], 'year': year, 'cases': max_val[str_year]}
(Also note that your definition of dataset
was syntaxtically incorrect)
{'country': 'Albania',
'continent': 'Europe',
'1990': 100,
'1991': 100,
'1992': 100,
'1993': 100},
^^ missing the close of the dictionary
CodePudding user response:
You can do in both ways:
Directly using max(lambda):
>>> max_dict = max(dataset, key=lambda x: x["1991"])
>>> new_dict = {'country':max_dict['country'], 'year':'1991', 'cases':max_dict['1991']}
>>> new_dict
{'country': 'Afghanistan', 'year': '1991', 'cases': 500}
>>>
Using manual looping:
>>> max_cntry=""
>>> max_1991=0
>>> for itm in dataset:
... if itm['1991'] > max_1991:
... max_1991 = itm['1991']
... max_cntry = itm['country']
...
>>> new_dict={'country':max_cntry, 'year':1991, 'cases':max_1991}
>>> print(new_dict)
{'country': 'Afghanistan', 'year': 1991, 'cases': 500}
>>>
You might need to handle appropriately if there is a match. There are 2 matches in sample dataset.