324
324

Reputation: 724

Is it possible to look up the key of a dictionary value under a certain number?

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.

Upvotes: 2

Views: 85

Answers (3)

Andrej Kesely
Andrej Kesely

Reputation: 195543

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

Upvotes: 3

JacobIRR
JacobIRR

Reputation: 8966

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.

Upvotes: 2

Paul Dlc
Paul Dlc

Reputation: 133

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)

Upvotes: 2

Related Questions