Home > OS >  Get max key of dictionary based on ratio key:value
Get max key of dictionary based on ratio key:value

Time:12-02

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.

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

I guess the following would be considered pretty pythonic :)

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

  • Related