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?
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.
min and max functions, when applied on dictionaries, they work on the keys of the 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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With