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.
CodePudding user response:
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.