开发者

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

开发者 https://www.devze.com 2022-12-27 12:53 出处:网络
self.mood_scale = { \'-30\':\"Panic\", \'-20\':\'Fear\', \'-10\':\'Concern\', \'0\':\'Normal\', \'10\':\'Satisfaction\',
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?


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


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.


Is that 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 with 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: Is much faster using the iterator

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 could be to keep track of the max/min values upon insertion and simply do mood_scale.min() / max()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号