If I have a Python dictionary, how do I get the key to the entry which contains the minimum value?
I was thinking about something to do with the min() function...
Given the input:
{320:1, 321:0, 322:3}
It would return 321.
If I have a Python dictionary, how do I get the key to the entry which contains the minimum value?
I was thinking about something to do with the min() function...
Given the input:
{320:1, 321:0, 322:3}
It would return 321.
For multiple keys which have equal lowest value, you can use a list comprehension:
d = {320:1, 321:0, 322:3, 323:0}
minval = min(d.values())
res = [k for k, v in d.items() if v==minval]
[321, 323]
An equivalent functional version:
res = list(filter(lambda x: d[x]==minval, d))
min(zip(d.values(), d.keys()))[1]
Use the zip function to create an iterator of tuples containing values and keys. Then wrap it with a min function which takes the minimum based on the first key. This returns a tuple containing (value, key) pair. The index of [1] is used to get the corresponding key.
I compared how the following three options perform:
import random, datetime
myDict = {}
for i in range( 10000000 ):
myDict[ i ] = random.randint( 0, 10000000 )
# OPTION 1
start = datetime.datetime.now()
sorted = []
for i in myDict:
sorted.append( ( i, myDict[ i ] ) )
sorted.sort( key = lambda x: x[1] )
print( sorted[0][0] )
end = datetime.datetime.now()
print( end - start )
# OPTION 2
start = datetime.datetime.now()
myDict_values = list( myDict.values() )
myDict_keys = list( myDict.keys() )
min_value = min( myDict_values )
print( myDict_keys[ myDict_values.index( min_value ) ] )
end = datetime.datetime.now()
print( end - start )
# OPTION 3
start = datetime.datetime.now()
print( min( myDict, key=myDict.get ) )
end = datetime.datetime.now()
print( end - start )
Sample output:
#option 1
236230
0:00:14.136808
#option 2
236230
0:00:00.458026
#option 3
236230
0:00:00.824048
To create an orderable class you have to override six special functions, so that it would be called by the min() function.
These methods are__lt__ , __le__, __gt__, __ge__, __eq__ , __ne__ in order they are less than, less than or equal, greater than, greater than or equal, equal, not equal.
For example, you should implement __lt__ as follows:
def __lt__(self, other):
return self.comparable_value < other.comparable_value
Then you can use the min function as follows:
minValue = min(yourList, key=(lambda k: yourList[k]))
This worked for me.