{'19': 3, '18': 7}
If I have a list like above, how do I find the max value and then print the key, value pair like:
(['18'], 7)
{'19': 3, '18': 7}
If I have a list like above, how do I find the max value and then print the key, value pair like:
(['18'], 7)
print max(data.iteritems(),key=lambda x:x[-1])
maybe? Im not really sure to be honest
There are more Pythonic ways to do these things, but I hope this illustrates the steps clearly for you. First we reverse the dictionary. Find the maximum
data = {'19': 3, '18': 7}
data_rev = dict([(value, key) for (key,value) in data.iteritems()])
print data_rev
max_val = max(data_rev.keys())
If you want to see it in a single statement:
out_tuple = ([dict([(value, key) for (key,value) in data.iteritems()])[max(data.values())]], max(data.values()))
The most straightforward method would be to just iterate and find it:
max_pair = None
for k,v in thedict.items():
if (max_pair is None) or (v > max_pair[1]):
max_pair = (k,v)
print max_pair
But the standard library provides some more "pythonic" ways to get at the same information..
from functools import partial
from operator import itemgetter
print max(thedict.items(), key=partial(itemgetter, 1))
This assumes you only want to get the first key where the max value appears. If instead you want all keys where the max value appears you have to do it in two passes (once to find the max, once to find all the keys).
max_val = max(thedict.values())
max_pair = (tuple(k for k in thedict if thedict[k] == max_val), max_val)