+1 vote
1 view
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

0 votes
2 answers
0 votes
1 answer
asked Jul 4, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...