Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find max , min of values in multidimensional dict

stats = {{'node100': {'load_1min': '0.58'}, 'node200': {'load_1min': '0.64'}, 'node28': {'load_1min': '0.69'}}

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.

like image 975
user1579557 Avatar asked Sep 16 '25 09:09

user1579557


1 Answers

Use the key argument to min and max:

>>> min(stats, key=lambda k:float(stats[k]['load_1min']))
'node100'
>>> max(stats, key=lambda k:float(stats[k]['load_1min']))
'node28'

In addition to iterating over the keys, this looks up every key in the dictionary. To avoid the extra lookups:

>>> min(stats.items(), key=lambda (k,v):float(v['load_1min']))
('node100', {'load_1min': '0.58'})
>>> max(stats.items(), key=lambda (k,v):float(v['load_1min']))
('node28', {'load_1min': '0.69'})
like image 177
NPE Avatar answered Sep 19 '25 03:09

NPE