Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get max key of dictionary based on ratio key:value

Here is my dictionary:

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading