Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to get the highest and lowest keys from a dictionary?

self.mood_scale = {
    '-30':"Panic",
    '-20':'Fear',
    '-10':'Concern',
    '0':'Normal',
    '10':'Satisfaction',
    '20':'Happiness',
    '30':'Euphoria'}

I need to set two variables: max_mood and min_mood, so I can put some limits on a ticker. What's the easiest way to get the lowest and the highest keys?

like image 642
Jorge Guberte Avatar asked Nov 27 '22 15:11

Jorge Guberte


2 Answers

>>> min(self.mood_scale, key=int)
'-30'
>>> max(self.mood_scale, key=int)
'30'
like image 123
SilentGhost Avatar answered Nov 30 '22 04:11

SilentGhost


This should do it:

max_mood = max(self.mood_scale)
min_mood = min(self.mood_scale)

Perhaps not the most efficient (since it has to get and traverse the list of keys twice), but certainly very obvious and clear.

UPDATE: I didn't realize your keys were strings. Since it sounds as if that was a mistake, I'll let this stand as is, but do note that it requires keys to be actual integers.

like image 22
unwind Avatar answered Nov 30 '22 04:11

unwind