3

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350

4 Answers4

6

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)
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

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]))
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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.

Community
  • 1
  • 1
Mixone
  • 1,327
  • 1
  • 13
  • 24
  • 1
    `for key, val in my_dict:` will give you a `TypeError` when trying to unpack that first integer yielded by the iterator constructed over the dict's keys. Did you mean `my_dict.items()` instead? – timgeb Sep 08 '18 at 21:30
  • You are absolutly right! I forgot to add the yield method in the dict object! – Mixone Sep 08 '18 at 21:33
  • 1
    Also, consider `float('-inf')` for the initial max values unless you want your solution to be restricted to positive keys and values. – timgeb Sep 08 '18 at 21:34
  • Was assuming all were positive integers true! – Mixone Sep 08 '18 at 21:34
0

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.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27