snickle
snickle

Reputation: 311

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?

Upvotes: 6

Views: 90

Answers (2)

Puffin GDI
Puffin GDI

Reputation: 1702

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]

Upvotes: 2

iruvar
iruvar

Reputation: 23374

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'

Upvotes: 6

Related Questions