Skip to content
Advertisement

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.

Advertisement

Answer

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'})
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement