Home > Enterprise >  Get largest key with largest value in python dictionary
Get largest key with largest value in python dictionary

Time:04-22

How can I get the largest key with the largest value in python dictionary. In the below example you can see 1 and 2 have same frequency. But i want to return the larger key.

nums = [1,2,2,3,1]
frq = {}
        
        for i in nums:
            if i not in frq:
                frq[i] = 1
            else:
                frq[i]  = 1
        
        frequency = max(frq, key=frq.get)
        print(frequency)

CodePudding user response:

Have your key function return a tuple of the value and the associated key. The first element of the tuple is compared first, the second will break ties.

>>> from collections import Counter
>>> nums = [1, 2, 2, 3, 1]
>>> frq = Counter(nums)
>>> max(frq, key=lambda n: (frq[n], n))
2

Note that collections.Counter builds the frq dictionary automatically given nums.

CodePudding user response:

You can use tuple comparison for the keys to compare keys based on their frequencies, and then tiebreak based on the actual value of the key only if the frequencies are the same:

frequency = max(frq, key=lambda x: (frq.get(x), x))

With this change, this outputs:

2

CodePudding user response:

You can try this, which sorts first on frequency and then on key:

nums = [1,2,2,3,1]
frq = {}
        
for i in nums:
    if i not in frq:
        frq[i] = 1
    else:
        frq[i]  = 1
        
frequency = max(frq, key=lambda x: (frq.get(x), x))
print(frequency)

Output:

2

Alternatively, you can use the Counter data type from Python's collections module to do some of the work for you:

from collections import Counter
nums = [1,2,2,3,1]
frequency = max(Counter(nums).items(), key=lambda x: (x[1], x[0]))[0]
print(frequency)

Here we pass items() to max(), so that both the key and the value are available to the key function (lambda). The result of max() will now be a (key, value) tuple, so we use [0] to get just the key as our result.

UPDATE: One other way to do it without overriding the default key argument to max() is this:

frequency = max((v, k) for k, v in Counter(nums).items())[1]
  • Related