Pythonic way to find weighted minimum and maximum keys from a dictionary

I am working with a dataset like this:

animals = { "antelope": { "latin": "Hippotragus equinus", "cool_factor": 1, "popularity": 6 }, "ostrich": { "latin": "Struthio camelus", "cool_factor": 3, "popularity": 3 }, "echidna": { "latin": "Tachyglossus aculeatus", "cool_factor": 5, "popularity": 1 } } 

What I'm looking for is to find the “least cool” and “coolest” animal, weighted by popularity, for example:

 > min_cool_weighted(animals) "echidna" > max_cool_weighted(animals) "ostrich" 

The solution that comes to me first is to create 3 arrays ( keys , cool_factors and popularities ), skip the dictionary, pop all the values ​​into 3 arrays, and then create a fourth array with each value, where weighted[i] = cool_factor[i] * popularity[i] , then take min / max and take the corresponding key from the key array. However, this is not like Pythonic.

Is there a better, more expressive way?

+6
source share
2 answers

max and min should be enough

 min(animals, key=lambda x: animals[x]["cool_factor"]*animals[x]["popularity"]) 'echidna' max(animals, key=lambda x: animals[x]["cool_factor"]*animals[x]["popularity"]) 'ostrich' 
+6
source

You can use sorted

Min:

 sorted(animals.iteritems(), key=lambda x:x[1]['cool_factor']*x[1]['popularity'])[0][0] 

Max:

 sorted(animals.iteritems(), key=lambda x:x[1]['cool_factor']*x[1]['popularity'])[-1][0] 
+2
source

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


All Articles