简体   繁体   中英

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?

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'

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM