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

Find the maximum out of dictionary or tuple

I am trying to find the maximum value in tuple and dictionary and right now I am doing it using loop but I really want to change the code from loop to list comprehension just as one liner code.

Here is the dictionary that I have and from which I need to extract max.

student1 = {First_Name: "ABC", Last_Name: "XYZ", Age: 23}
student2 = {First_Name: "ABC", Last_Name: "XYZ", Age: 23, Address: "TYU"}
student3 = {First_Name: "ABC", Last_Name: "XYZ", Age: 23, Address: "TYUZYX"}

A = {student_One: student1, student_Two: student2, student_three: student3}

The max should be student_3.

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

>Solution :

It would be really nice if you can post your current solution so that I can help you out better but what I am understanding from your question is that instead of loops, you want to use a one-liner code to find the maximum. Here are some of the ways to achieve that.

Using max function in python

If your dictionary name is dict then you can use the following code to find the maximum.

 max(dict, key=dict.get)

OR

 dict[max(dict, key=dict.get)]

OR

 max(dict)

You can also use operator.itemgetter

max(dict.iteritems(), key=operator.itemgetter(1))[0]

There is a much faster way to get the maximum from the dictionary in Python

def keywithmaxval(d):
 # a) create a list of the dict's keys and values; 
 # b) return the key with the max value
 v=list(d.values())
 k=list(d.keys())
 return k[v.index(max(v))]

You can also use Lambda operator

max(dict.items(), key = lambda k : dict[1])

For Tuple

There are many ways in the case of tuple also but the max function in Python is the fastest way to find the maximum from tuples.

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