JavaScript
x
2
1
stats = {{'node100': {'load_1min': '0.58'}, 'node200': {'load_1min': '0.64'}, 'node28': {'load_1min': '0.69'}}
2
I want to find
1. key with max Load_1min value ,
2. key with min Load_1min value ,
3. avg value of all the load_min keys for stats.
Last one is simple – But 1st two are tough. I tried max function but failed.
Advertisement
Answer
Use the key
argument to min
and max
:
JavaScript
1
5
1
>>> min(stats, key=lambda k:float(stats[k]['load_1min']))
2
'node100'
3
>>> max(stats, key=lambda k:float(stats[k]['load_1min']))
4
'node28'
5
In addition to iterating over the keys, this looks up every key in the dictionary. To avoid the extra lookups:
JavaScript
1
5
1
>>> min(stats.items(), key=lambda (k,v):float(v['load_1min']))
2
('node100', {'load_1min': '0.58'})
3
>>> max(stats.items(), key=lambda (k,v):float(v['load_1min']))
4
('node28', {'load_1min': '0.69'})
5