What is the easiest way to get the highest and lowest dictionary keys?

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

I need to set two variables: max_moodand min_mood, so I can set some restrictions on the ticker. What is the easiest way to get the lowest and highest keys?

+3
source share
3 answers

This should do it:

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

It may not be the most efficient (since it has to iterate and iterate over the list of keys twice), but it is certainly very clear and understandable.

UPDATE: , . , , , , , , .

+8
>>> min(self.mood_scale, key=int)
'-30'
>>> max(self.mood_scale, key=int)
'30'
+12

Is this valid Python? I think you mean:

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

print mood_scale[str(min(map(int,mood_scale)))]
print mood_scale[str(max(map(int,mood_scale)))]

Outputs

Panic Euphoria

Much better and faster using ints as keys

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

print mood_scale[min(mood_scale))]
print mood_scale[max(mood_scale))]

Edit 2: Iterator works faster

print timeit.timeit( lambda: mood_scale[min(mood_scale.keys())])
print timeit.timeit( lambda: mood_scale[min(mood_scale)])
1.05913901329
0.662925004959

Another solution might be to keep track of max / min values ​​on insertion and just do mood_scale.min () / max ()

+7
source

Source: https://habr.com/ru/post/1741241/


All Articles