Getting the keys corresponding to the values (in tuple format) containing the largest number

Question:

I have a dictionary as follows: the keys are integers from 1 to 109, and the values are either False or True. If True, the value will be a tuple containing a number, such as (True, 0.9). The sample dictionary looks like this:

myDictionary = {1: False, 
                2: (True, 0.9),
                3: False,
                4: (True, 0.3),
                5: (True, 0.11), 
                ...
                ...
                107: (True, 0.9),
                108: False,
                109: (True, 0.84)}

I would like to get the keys corresponding to the values that contain the largest number in the tuple. In the snippet above, it would be 2 and 107. If more than 1 pair contain the largest value, I would like to have them both. Any suggestions on how to accomplish this? Thanks!

Asked By: Paul Jiang

||

Answers:

Start by finding the maximum value:

>>> [v[1] for k, v in myDictionary.items() if isinstance(v, tuple)]
[0.9, 0.3, 0.11, 0.9, 0.84]
>>> max_val = max(v[1] for k, v in myDictionary.items() if isinstance(v, tuple))

and then find the keys corresponding to that value:

>>> [k for k, v in myDictionary.items() if isinstance(v, tuple) and v[1] == max_val]
[2, 107]
Answered By: Samwise

Use max with a custom key function get the max value, then just filter the dict for the relevant keys:

d = {
    1: False,
    2: (True, 0.9),
    3: False,
    4: (True, 0.3),
    5: (True, 0.11),
    107: (True, 0.9),
    108: False,
    109: (True, 0.84),
}

max_value = max(d.values(), key=lambda x: x or (False, 0))
max_keys = [k for k, v in d.items() if v == max_value]

## max_keys: [2, 107]
Answered By: Tomer Ariel

You can achieve this with a single pass over the dictionary’s items:

myDictionary = {1: False, 
                2: (True, 0.9),
                3: False,
                4: (True, 0.3),
                5: (True, 0.11), 
                107: (True, 0.9),
                108: False,
                109: (True, 0.84)}

m = float('-inf')
keys = None

for k, v in myDictionary.items():
    if v:
        _, n = v
        if n > m:
            m = n
            keys = [k]
        elif n == m:
            keys.append(k)

print(keys)

Output:

[2, 107]
Answered By: Fred
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.