Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (1.6k points)

I have a dict and I want to find out the max and min value with its key.

Ex-

dict_value={‘p’:2 ,’q’:5,’r’:8,’s’:1}

 Output-

Max : 8 ,key is r

Min : 1, key is s

I know how to get min and max values from dict but is there any way to get values and keys in one statement?

max([i for i in dic.values()])

min([i for i in dic.values()])

1 Answer

0 votes
by (10.9k points)

Yes, just use max and min functions with dict.get.

dict.get return the value for key if the key is present in the dictionary.

Ex-

max_value = max(dict_value, key=mydict.get)  

print(max_value, dict_value[max_value])

Output-

r 8

min_value = min(dict_value, key=mydict.get)  

print(min_value, dict_value[min_value])

Output-

s 1

Related questions

Browse Categories

...