For example, I have a dictionary like such:
sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}
I know that I can use the get()
function to get the value of a particular key, but is there a way to do the opposite in a conditional manner?
For example, what if I wanted to get the key for maximum number in sampleDict
. Is there a good function or set of functions I can use to quickly and efficiently get that value? I've tried a quick Google search, but I'm not coming up with what I want. In this example, I would want to receive the number 1
since the value for key 1
is the maximum value in the dictionary.
CodePudding user response:
To get with max value you can use max()
builtin function:
sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}
max_key = max(sampleDict, key=sampleDict.get)
print(max_key)
Prints:
1
CodePudding user response:
This return a array of keys that have the value you search.
keys = [k for k, v in sampleDict.items() if v == value]
print(keys)
CodePudding user response:
You can use a loop to find the key which matches the max value:
sampleDict = {0: 0, 1: 10, 2: 2, 3: 3, 4: 4}
def foo(sampleDict):
m = max(sampleDict.values())
for k, v in sampleDict.items():
if v == m:
return k
print(foo(sampleDict))
Result: 1
This obviously does not account for any dupe max values. It just finds the first value that matches the max.
In terms of performance, this assumes the input size is not massive.
If we needed to make it more efficient, we could calculate the maximum as we iterate.