Get max key of dictionary based on ratio key:value

Question:

Here is my dictionary:

inventory = {60: 20, 100: 50, 120: 30}

Keys are total cost of goods [$] and values are available weight [lb].

I need to find a way to get key based on the highest cost per pound.

I have already tried using:

most_expensive = max(inventory, key={fucntion that calculates the ratio})

But cannot guess the pythonic way to do that.

Thank you in advance.

Asked By: Pacool1234

||

Answers:

I guess the following would be considered pretty pythonic 🙂

max([key/value for key, value in inventory.items()])

Answered By: ViggoTW

What you are doing is correct. By using the key argument you can calculate the ratio. The thing you are missing is that you want to compare the key and values, therefore you can use the inventory.items().

The code would be:

max(inventory.items(), key=lambda x: x[0]/x[1])

Which will result in the following if I use your values:

(120, 30)

In order to get only the key, you have to get the first element of the answer.

Answered By: Thymen

You can get the key of the maximum ratio directly with a key function that takes a key and returns the ratio:

max(inventory, key=lambda k: k / inventory[k])

This returns, given your sample input:

120
Answered By: blhsing
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.