In Python, given a dictionary object e.g:
1 | data = {"abc": 2, "cde": 10, "def": -1} |
data = {"abc": 2, "cde": 10, "def": -1}
What are the ways to return the key which has corresponding largest (or smallest) value in this case the key “cde” has the largest value 10.
The max() won’t work as it returns the maximum key:
1 | print(max(data)) # print "def" |
print(max(data)) # print "def"
It is the same as max(data.keys())
1 | print(max(data.keys()) # print "def" |
print(max(data.keys()) # print "def"
How about max(data.values())? It gives you largest value but not key:
1 | print(max(data.values()) # print 10 |
print(max(data.values()) # print 10
However, one workaround is to check afterwards which key correspond to this value:
1 2 3 | for key in data: if key == max(data.values()): # save this in a variable print(key) # print "cdf" |
for key in data: if key == max(data.values()): # save this in a variable print(key) # print "cdf"
We can pass the key comparator using data.get function:
1 | print(max(data, key=data.get)) # print cdf |
print(max(data, key=data.get)) # print cdf
This is the same as using lambda but make sure to change the first parameter to .items() which compares the tuple instead of keys.
1 | print(max(data.items(), key=lambda x:x[1])[0]) # print cdf |
print(max(data.items(), key=lambda x:x[1])[0]) # print cdf
Another one-liner in Python to retreive the key which has the largest/smallest value:
1 | print(max([(x, y) for y, x in data.items()])[1]) # print cdf |
print(max([(x, y) for y, x in data.items()])[1]) # print cdf
This is based on the idea of swapping key-value pairs first and then retrieve the max item (with largest/smallest key) then returning its value – which should be the original key that has the largest/smallest value.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Teaching Kids Programming - Maximum Level Sum of a Binary Tree using DFS Algorithm
Next Post: Teaching Kids Programming - Palindrome Count Algorithm