Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to find key of weighted minimum and maximum from a dictionary

I'm working with a dataset similar to 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 to do is find the "least cool" and "coolest" animal weighted by popularity, such that:

> 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), loop through the dictionary, push all the values into the 3 arrays, then create a fourth array with each value where weighted[i] = cool_factor[i] * popularity[i], then take the min/max and grab the corresponding key from the key array. However, this doesn't seem very Pythonic.

Is there a better, more expressive way?

like image 436
snickle Avatar asked Nov 08 '13 01:11

snickle


People also ask

How do you find the key with a maximum value in a dictionary?

The simplest way to get the max value of a Python dictionary is to use the max() function. The function allows us to get the maximum value of any iterable.

Will MAX () and MIN () always work for a dictionary?

min and max functions, when applied on dictionaries, they work on the keys of the dictionary.

How do you find the minimum key in a dictionary?

To find the minimum value in a Python dictionary you can use the min() built-in function applied to the result of the dictionary values() method.


2 Answers

max and min should suffice

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'
like image 181
iruvar Avatar answered Sep 19 '22 00:09

iruvar


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]
like image 28
Puffin GDI Avatar answered Sep 18 '22 00:09

Puffin GDI