'Return key according to value of python dictionary
I have a Python dictionary say
d = {"david":30, "vivian":40, "tom":20,"echo":40}
My goal is:
- To return the key with the largest value.
- In case there is a tie in the value, the key with the shortest length (number of letters) will be prioritized. So, in this case, "echo" will be returned.
I can achieve first goal with:
max_key = max(d, key=d.get)
How can I achieve the second goal?
Solution 1:[1]
There may be a more concise way to do this but this seems to work:
d = {"david":30, "vivian":40, "tom":20,"echo":40}
print(sorted([(v, k) for k, v in d.items()], key=lambda x: (x[0], -len(x[1])))[-1])
Output:
(40, 'echo')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Albert Winestein |
