Home > Back-end >  Iterate through values of dictionary
Iterate through values of dictionary

Time:01-13

I have been trying to iterate through the values of my dictionary. The dictionary looks like this:

temperature = {
    'June': [25,25,26,27,25,25,24,27,28,28,31,32,33],
    'July': [34,34,36,39,39,38,39,37,39,41,41,39,37],
    'August': [37,37,36,37,35,35,34,37,38,34,32,33,31],
}

and I am trying to find the month with the max value. So far my code i up to this point:

def minEl(dictionary):
    for key in dictionary:
        for i in key:
            for o in i:
                l = min(((k,v[o]) for k,v in temperature.items()),key=lambda x:x[o])
                return l

But the error message shows that I can't use a letter as list indices.

CodePudding user response:

You can use a dictionary comprehension to extract the max value for every month, and then use the max() function again by providing the resulting dictionary's values as the key to compare:

>>> max_per_month = {k:max(temperature[k]) for k in temperature}
>>> max_per_month
{'June': 33, 'July': 41, 'August': 38}
>>> max(max_per_month, key=max_per_month.get)
'July'

EDIT: Actually, we can make it even more succint with a one-liner that's readable:

>>> t = {'June': [39, 40, 41], 'July': [39, 40], 'August': [40, 41]}
>>> max(t, key=lambda x: max(t[x]))
'June'
>>> t = {'June': [39, 40, 41], 'July': [39, 40], 'August': [40, 41, 42]}
>>> max(t, key=lambda x: max(t[x]))
'August'
>>> t = {'June': [39, 40, 41], 'July': [39, 40, 42], 'August': [40, 41, 42]}
>>> max(t, key=lambda x: max(t[x]))
'July'

We get month with the max by providing the key with the max of every month (max(t[x])).

CodePudding user response:

You can use dict.setdefault to create a new dictionary where the keys are max temperatures in each month and values are months.

out = {}
for k, lst in temperature.items():
    out.setdefault(max(lst), []).append(k)

Then you can find the month that had the hottest day simply by:

hottest_month = out[max(out)]

Output:

['July']
  •  Tags:  
  • Related