Find the key of maximum values of maximum key in a dictionary in case of duplicates of values

Viewed 339

In Python I want to find the maximum value out of dictionary which has the duplicates, for example :

my_dict = {1: 0, 12: 2, 36: 2, 24: 2, 33: 2, 4: 1}

and the maximum value is 2.

And I want to find the maximum key of the maximum value which is 36:2 in this example.

4 Answers

You can feed the dict's items into the max builtin function.

>>> max(my_dict.items(), key=lambda t: (t[1], t[0]))
(36, 2)

The key-function specifies that the value (second element of an item) should be considered first. If the values are the same during the comparison of two (key, value) pairs, the key (first element of an item) is examined.

edit:

alternatively, maybe a little slicker:

>>> max(my_dict.items(), key=lambda t: t[::-1])
(36, 2)

You could call max on the dictionary's items with a custom order that takes the value first and the key second:

max(my_dict.items(), key=lambda i : (i[1], i[0]))

Assuming all your keys are positive integers.

Then the complexity of this issue is twofold, first we need to find the maximum values, then we can pair it with a maximum key.

I would do something like this:

max_key = -1
max_val = -1
for key, val in my_dict.items():
    if int(val) >= max_val:
        max_val = int(val)
        if int(key) > max_key:
            max_key = int(key)
 print("Max value: {}\nMax key: {}".format(max_val, max_key)

That should do it.

EDIT

Using builtin function max probably works better, this code basically replicates what max is doing more or less.

Here is a sample example:

my_dict = {1: 0, 12: 2, 36: 2, 24: 2, 33: 2, 4: 1}
maxValue = []
maximum = 0
maxKey = 0
maxKeys = []

for key, value in my_dict.items():
     if value >= maximum:
          maxValue.append(value)


number = max(maxValue)

for key, value in my_dict.items():
    if key > maxKey:
         maxKeys.append(key)

number_1 = max(maxKeys)

print('{}: {}'.format(number_1, number))

And here is your output:

36: 2

We can essentially iterate through each value and each key and add them to a list and find the max value. We can then make a print statement using the .format() method that will print the results.

Related