Print maximum value in dict with key

My dict is like,

{'A':4,'B':10,'C':0,'D':87} 

I want to find the maximum value with its key and the minimum value using my key.

The way out will be

max: 87, D key

min: 0, key C

I know how to get min and max values ​​from a dict. Is there a way to get the value and key in one statement?

 max([i for i in dic.values()]) min([i for i in dic.values()]) 
+7
source share
3 answers

You can use max and min with dict.get :

 maximum = max(mydict, key=mydict.get) # Just use 'min' instead of 'max' for minimum. print(maximum, mydict[maximum]) # D 87 
+35
source

The key should work with dict elements (i.e. key-value pairs). Then, using the second element of the element as the max key (as opposed to the dict key), you can easily extract the highest value and the key associated with it.

  mydict = {'A':4,'B':10,'C':0,'D':87} >>> max(mydict.items(), key=lambda k: k[1]) ('D', 87) >>> min(mydict.items(), key=lambda k: k[1]) ('C', 0) 
+7
source

just:

  mydict = {'A':4,'B':10,'C':0,'D':87} max(mydict.values()) min(mydict.values()) 

values will provide you with a list of values ​​from the dictionary. The max function gives the maximum value. min minimum function value

and you want a key

+2
source

Source: https://habr.com/ru/post/978040/


All Articles