print highest value in dict with key
just :
mydict = {'A':4,'B':10,'C':0,'D':87}
max(mydict.items(), key=lambda x: x[1])
You could use 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
The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max
key (as opposed to the dict
key) you can easily extract the highest value and its associated key.
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)